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
+13.6k Golang : Get user input until a command or receive a word to stop
+8.5k Linux/Unix : fatal: the Postfix mail system is already running
+25k Golang : Create PDF file from HTML file
+5.4k Golang : What is StructTag and how to get StructTag's value?
+18.8k Golang : How to make function callback or pass value from function as parameter?
+24.6k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+7.8k Golang : Load DSA public key from file example
+5.8k Cash Flow : 50 days to pay your credit card debt
+8k Golang : Get all countries phone codes
+9.6k Golang : Copy map(hash table) example
+22.7k Golang : Set and Get HTTP request headers example