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.1k Golang : How to get a user home directory path?
+6.5k Golang : Handling image beyond OpenCV video capture boundary
+19.6k Golang : Get current URL example
+17.1k Golang : Get number of CPU cores
+41.4k Golang : Convert string to array/slice
+22k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+48.2k Golang : How to convert JSON string to map and slice
+21.8k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+8.6k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+6.9k Golang : Calculate BMI and risk category
+27.6k Golang : dial tcp: too many colons in address