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
+18.1k Golang : Defer function inside init()
+28.7k Golang : Change a file last modified date and time
+42.1k Golang : How do I convert int to uint8?
+5.7k Golang : Shortening import identifier
+6.6k Golang : Convert an executable file into []byte example
+21.6k Curl usage examples with Golang
+9.4k Golang : Temperatures conversion example
+11.5k Golang : Post data with url.Values{}
+19.3k Golang : Execute shell command
+8.4k Golang : Count leading or ending zeros(any item of interest) example
+10.2k Golang : Edge detection with Sobel method
+5.5k Unix/Linux/MacOSx : How to remove an environment variable ?