了解Go中的fmt软件包

Where comes the 2 from in the output ?

I wrote a program that reads from STDIN and return values to STDOUT.

package main

import "fmt"

func main() {
    var steps, i, a, b int
    fmt.Scanf("%d", &steps)
    for i = 0; i <= steps; i++ {
        fmt.Scanf("%d", &a)
        fmt.Scanf("%d", &b)
        fmt.Println(a + b)
    }
}

I have a input file

2
2 5
4           8

When I run the program with go run program.go < input I get:

2
7
12

Instead of:

7
12

Why ?

After having tried it, it turns out that (on my Linux machine) if the input file is in "Windows format", with CRLF line ends, it will give your behaviour. If the input file is in "Unix format, with LF line ends, it works as expected. You also get the same behaviour if you add garbage at the end of the lines, for example like this:

2x
2 5x
4           8x

So it seems that it doesn't recognise CR as a whitespace character, which can be skipped by the "%d" format specifier, and stops reading when it finds it, like it does with the x in my example above.

I think this should be called a bug. It certainly is inconvenient, since it isn't uncommon to encounter text files that happen to have Windows-style line ends when working on Linux.

i <= steps should be i < steps.