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.2k Golang : Delete item from slice based on index/key position
+5.2k Linux/Unix : Commands that you need to be careful about
+9.2k Golang : Allow Cross-Origin Resource Sharing request
+5.6k Golang : Skip or discard items of non-interest when iterating example
+13.9k Golang : Force download file example
+25.9k PHP : Count number of JSON items/objects
+8.7k PHP : Get coordinates latitude/longitude from string
+39.7k Golang : How to check if a string contains another sub-string?
+8.3k Golang : Changing a RGBA image number of channels with OpenCV
+18.3k Golang : Determine if directory is empty with os.File.Readdir() function
+10.8k Golang : Convert a rune to unicode style string \u
+10k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example