Need explanation for the output

package main

import (
        "fmt"
        "os"
)

func main() {

        var a,b,e,f int

        fmt.Scanf("%d Scanf %d", &a, &b)
        fmt.Scanf("%d Scanf %d", &e, &f)
        fmt.Fprintf(os.Stdout, "%d - %d\n", a, b)
        fmt.Fprintf(os.Stdout, "%d - %d\n", e, f)
}

I ran the above code as

echo 1 2 3 4 5 6 | go run program.go

and the output that I got is

1 - 0
3 - 0

I just want to understand step by step for fmt.Scanf() function why the output came what it came…

Scanf parses the arguments following the format string you gave it. So the first call expects to read num Scanf other_num to assing to num to a and other_num to b. You’ll see that if you call it like on of these:

echo 1 Scanf 2\n3 Scanf 4 | ./scanf-test
echo 1 Scanf 2 3 Scanf 4 | ./scanf-test

You’ll get this output as expected:

1 - 2
3 - 4

In your case, calling it with 1 2 3 4 5 6 made it scan 1, discard 2 as it didn’t follow the format, and then went on to scan 3 on the next call, which discarded 4 and finally printed everything.

You can read more about it here: https://golang.org/pkg/fmt/

1 Like