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.7k Golang : convert int to string
+8.2k How to show different content from website server when AdBlock is detected?
+18.2k Golang : Get command line arguments
+5.6k Golang : Detect words using using consecutive letters in a given string
+19.2k Mac OSX : Homebrew and Golang
+17.9k Golang : How to make a file read only and set it to writable again?
+26.6k Golang : Encrypt and decrypt data with AES crypto
+9.4k Golang : Scramble and unscramble text message by randomly replacing words
+4.9k HTTP common errors and their meaning explained
+9.5k Golang : Get all countries currencies code in JSON format
+4.9k Nginx and PageSpeed build from source CentOS example