dsv17139 2017-09-29 06:07
浏览 90
已采纳

为什么在Go中的fmt.Scanf中使用:=总是返回1? [关闭]

Why I use:

var n int
a, _ := fmt.Scanf("%d",&n)

Then a == 1, n has changed its value by input.

  • 写回答

1条回答 默认 最新

  • dongxu0690 2017-09-29 06:10
    关注

    fmt.Scanf() returns the number of successfully scanned items:

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

    So if your input is a valid integer number fitting into an int, fmt.Scanf() will succeed to parse it and store it in n, and so it will return 1.

    Should you input an invalid number (e.g. the string value "a"), scanning would not succeed, so 0 would be returned along with a non-nil error, like in this example:

    var n int
    a, err := fmt.Sscanf("a", "%d", &n)
    fmt.Println(a, err)
    

    Which outputs (try it on the Go Playground):

    0 expected integer
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制