douchen2595 2014-06-03 01:46
浏览 170
已采纳

fmt.Scanln预期的换行错误

I'm trying to learn Go, but stuck with this one: http://ideone.com/hbCamr or http://ideone.com/OvRw7t

package main
import "fmt"

func main(){
  var i int
  var f float64
  var s string

  _, err := fmt.Scan(&i)
  if err == nil {
    fmt.Println("read 1 integer: ",i)
  } else {
    fmt.Println("Error: ",err)
  }

  _, err = fmt.Scan(&f)
  if err == nil {
    fmt.Println("read 1 float64: ",f)
  } else {
    fmt.Println("Error: ",err)
  }
  _, err = fmt.Scan(&s)
  if err == nil {
    fmt.Println("read 1 string: ",s)
  } else {
    fmt.Println("Error: ",err)
  }

  _, err = fmt.Scanln(&s)
  if err == nil {
    fmt.Println("read 1 line: ",s)
  } else {
    fmt.Println("Error: ",err)
  }
}

for this input:

123
123.456
everybody loves ice cream

the output was:

read 1 integer:  123
read 1 float64:  123.456
read 1 string:  everybody
Error:  Scan: expected newline

is this the expected behavior? why doesn't it work like C++ getline? http://ideone.com/Wx8z5o

  • 写回答

1条回答 默认 最新

  • doumo2501 2014-06-03 01:56
    关注

    The answer is in the documentation of Scanln:

    Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

    Scan behaves as documented as well:

    Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

    To conclude: Scan puts each word (a string separated by space) into a corresponding argument, treating newlines as space. Scanln does the same but treats newlines as a stop character, not parsing any further after that.

    In case you want to read a line ( at the end) use bufio.Reader and its ReadString method:

    line, err := buffer.ReadString('
    ')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘