Golang : Read until certain character to break for loop
Encounter a situation where I need to tell the editor that is time to save the input and exit while working on the previous tutorial to show how to create a simple text based editor to accept screen input and save the content directly into a file.
Basically, I need to tell the program when to stop scanning or reading from the input source and break the for loop.
To do that... just intercept input from scanner.Text() and if it matches the criteria, break the for loop.
Code fragment from https://www.socketloop.com/tutorials/golang-text-file-editor-accept-input-from-screen-and-save-to-file
var userInput []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
if line == "." {
break // to stop writing enter . (period) and press enter
}
userInput = append(userInput, line+"\n")
}
See also : Golang : Text file editor (accept input from screen and save to file)
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+20.1k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+12.7k Golang : Transform comma separated string to slice example
+22.3k Golang : How to run Golang application such as web server in the background or as daemon?
+16.1k Golang : Get sub string example
+4.8k Chrome : How to block socketloop.com links in Google SERP?
+27.3k Golang : Find files by name - cross platform example
+5.8k Linux : Disable and enable IPv4 forwarding
+9.5k Golang : Scramble and unscramble text message by randomly replacing words
+10.7k Android Studio : Simple input textbox and intercept key example
+28.1k Golang : Move file to another directory
+5.4k Javascript : Shuffle or randomize array example
+11k Golang : Removes punctuation or defined delimiter from the user's input