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('
    ')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页