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

报告相同问题?