dsv17139
dsv17139
2017-09-29 06:07

为什么在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 dongxu0690 4年前

    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
    
    点赞 评论 复制链接分享

相关推荐