1

When I use "bufio" package, the standard code is just like:

input := bufio.NewScanner(os.Stdin)
for input.Scan() {
    // xxxxx
}

When I run the program, the for-loop can't stop whatever I input. I have tried newline, space, ctrl-d, ctrl-z. According to the document, a blank newline should be able to stop the program.

The program is running under Windows 7 CMD environment, or mingw-bash.

Thanks.

Hewei Liu
  • 120
  • 1
  • 7

1 Answers1

3

You may input some specific string as a signal to stop the loop. In the below example, whenever "quit" is entered, the loop breaks.

package main

import (
    "bufio"
    "os"
)

func main() {
    input := bufio.NewScanner(os.Stdin)
    for input.Scan() {
        indata := input.Text()
        if indata == "quit" {
            break
        }
    }
}
Nipun Talukdar
  • 4,975
  • 6
  • 30
  • 42
  • 1
    Thanks for the answer. – Hewei Liu Apr 12 '16 at 06:00
  • You can simulate `EOF` in terminal. On **Linux** is `CTRL + D`, on **Windows** `CTRL + Z`: [source](https://stackoverflow.com/questions/1118957/c-how-to-simulate-an-eof) – rgb Aug 19 '19 at 18:22