I have two (or potentially more) lines of input that I would like the program to take. eg.
1 2 3 4
5 6 7 8
According to the official doc, using
for scanner.Scan() {
}
will cause infinite lines to be scan until it reach EOF or error, are there other functions that will take two lines of input instead?
It's traditional to end user input from stdin with an empty (zero length) line. For example,
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func main() {
snr := bufio.NewScanner(os.Stdin)
enter := "Enter a line of data:"
for fmt.Println(enter); snr.Scan(); fmt.Println(enter) {
line := snr.Text()
if len(line) == 0 {
break
}
fields := strings.Fields(line)
fmt.Printf("Fields: %q
", fields)
}
if err := snr.Err(); err != nil {
if err != io.EOF {
fmt.Fprintln(os.Stderr, err)
}
}
}
Output:
$ go run data.go
Enter a line of data:
1 2 3 4
Fields: ["1" "2" "3" "4"]
Enter a line of data:
5 6 7 8
Fields: ["5" "6" "7" "8"]
Enter a line of data:
$
Ask the user to press "CTRL + D", that signals the EOF from the terminal, your above code should work without any change.
One way to do this is to verify if the scanner has reached the end of the file.
var s scanner.Scanner
file, _ := os.Open("file.go") // return io.Reader
s.Init(file) // needs io.Reader
var character rune
character = s.Scan()
for character != scanner.EOF {
// here your code
}