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
+4.3k Python : Convert(cast) string to bytes example
+4.3k JavaScript/JQuery : Redirect page examples
+7.4k Golang : Ackermann function example
+16.6k Golang : Put UTF8 text on OpenCV video capture image frame
+8.9k Golang : Check a web page existence with HEAD request example
+5.3k Golang : How to get capacity of a slice or array?
+11.2k Golang : Forwarding a local port to a remote server example
+31.3k Golang : How to check if a date is within certain range?
+6.4k Golang : Not able to grep log.Println() output
+8k Golang : Find the length of big.Int variable example
+5.7k Golang : Calculate pivot points for a cross
+7k Golang : Handle Palindrome string with case sensitivity and unicode