Input gap. Scan ()

I have this simple code to read all input from the console:

input := bufio.NewScanner(os.Stdin) //Creating a Scanner that will read the input from the console

for input.Scan() {
    if input.Text() == "end" { break } //Break out of input loop when the user types the word "end"
    fmt.Println(input.Text())
}

The code is how it works. What I want to do is get rid of the if clause. In my understanding of the documentation, if the line is empty, it input.Scan()should return false and, therefore, exit the loop.

The scan advances the scanner to the next token, which will then be available through the Bytes or Text method. It returns false when scanning stops, either reaching the end of the input, or an error. After Scan returns false, the Err method will return any error that occurred during the scan, except that if it was io.EOF, Err will return zero. Panic scan if the split function returns 100 empty tokens without advancing the input. This is a common error mode for scanners.

I misinterpreted the documentation, and is it really necessary that such an if-break condition breaks out? (I am using Go 1.5.2, starting the program using "go run".)

+14
source share
5 answers

, . - ScanLines.

:

ScanLines - , , . . - . \r?\n. , .

:

  • : , .
  • , : , , . , .

EOF ( ). , Ctrl-D, .

+22

.

, , , . if, , , , :

    input := bufio.NewScanner(os.Stdin) //Creating a Scanner that will read the input from the console

    for input.Scan() {
        if input.Text() == "" {
            break
        } 
        fmt.Println(input.Text())
    }
+4

.

, , , .

. , , .. EOF .

Linux "CTRL + D", EOF .

, "CTRL + D" . , , "CTRL + D" .

0

Mac, Ctrl + D . , Ctrl + D 2 .

0
source

CTRL+Dto break, if you want to enter data easily, you can use cat input.txt | go run script.go cat input.txt | go run script.goor go run script.go < input.txt.

0
source

Source: https://habr.com/ru/post/1621869/


All Articles