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
+6.3k Android Studio : AlertDialog to get user attention example
+7.9k Golang : Populate or initialize struct with values example
+22.8k Golang : Daemonizing a simple web server process example
+24.6k Mac/Linux and Golang : Fix bind: address already in use error
+8.7k Golang : Detect number of faces or vehicles in a photo
+10.9k Golang : List running EC2 instances and descriptions
+5.9k Golang : constant 20013 overflows byte error message
+7.7k Golang : Find network service name from given port and protocol
+6.9k Golang : Load DSA public key from file example
+8.2k Golang : Create unique title slugs example
+10.5k Golang : Sort and reverse sort a slice of runes
+4k Golang : Convert lines of string into list for delete and insert operation