dqqs64238 2015-12-27 13:51
浏览 62
已采纳

突破输入.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 as it is works. What I want to do is get rid of the if-clause. In my understanding of the documentation if a line is empty input.Scan() should return false and therefore break out of the loop.

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

Am I misinterpreting the documentation and it is actually necessary to have such a if-clause to break out? (I'm using Go 1.5.2 running the program using "go run".)

  • 写回答

5条回答 默认 最新

  • dougan4663 2015-12-27 15:27
    关注

    I think you misread the documentation. The default scanner is ScanLines function.

    Documentation says:

    ScanLines is a split function for a Scanner that returns each line of text, stripped of any trailing end-of-line marker. The returned line may be empty. The end-of-line marker is one optional carriage return followed by one mandatory newline. In regular expression notation, it is ? . The last non-empty line of input will be returned even if it has no newline.

    Two important points here:

    • The return line may be empty: It means it returns empty lines.
    • The last non-empty line of input will be returned even if it has no newline: It means the last line of a file is always returned if it is non empty. It does not mean however an empty line end the stream.

    The scanner will stop on EOF (End Of File). Typing Ctrl-D for example will send end of file and stop the scanner.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测