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.3k Golang : Iterating Elements Over A List
+12.4k Golang : Transform comma separated string to slice example
+4.5k PHP : Extract part of a string starting from the middle
+14.2k Golang : Send email with attachment(RFC2822) using Gmail API example
+6.7k Golang : Calculate BMI and risk category
+19.1k Golang : Fix cannot download, $GOPATH not set error
+10.1k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+17.1k Golang : Check if IP address is version 4 or 6
+4.7k JQuery : Calling a function inside Jquery(document) block
+14k Golang : Get uploaded file name or access uploaded files
+9.9k Golang : Compare files modify date example
+9.2k Golang : Qt Yes No and Quit message box example