Understanding the fmt package in go

Where is 2

the exit?

I wrote a program that reads from STDIN and returns 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 an input file

2
2 5
4           8

      

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

, I get:

2
7
12

      

Instead:

7
12

      

Why?

+3


source to share


2 answers


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

2x
2 5x
4           8x

      



So it seems that it does not recognize CR as a whitespace character that can be missed by the "% d" format specifier and stops reading when it finds it, as it does with x in my example above.

I think this should be called a bug. This is certainly inconvenient, as it is not uncommon to find text files that tend to end up in Windows style when running on Linux.

+3


source


i <= steps

should be i < steps

.



0


source







All Articles