A little but still anoying problem with the STD I/O function

Hi, I’m new at Go-lang but I’ve been programming at C++ since time ago. I decided to learn Go and for me it’s no better way to do it than watching some structured videos about it and then solving programming problems from SPOJ, Codeforces, etc.

I’m trying to solve an almost trivial problem right now because it’s logic is not that hard but I think I’m having problems at the standard input part and would like to know if anyone here can help me with it, i’ve been trying to figure out why does it happen but still have no solid answer.

Here is the input example, the output I get and in case you wonder, the problem link is here aswell:
(Input Example)
2
2
1 2
3 4
3
1 2 3
4 5 6

(Output Example)
[1 1]
[3 3]
[1 3 4]
[6 6 6]

(Problem Link)

My current suspicions are that it has something to do with the fmt.Scanf, like it doesn’t go forward on the console line element by element and always read the same first element (which is nonsense) but I haven’t found anything explaining the why, even the function description.

Thank you very much in advance.

package main

import (

    "fmt"

)

func main() {

    var (

        cases, couples int

        array          []int

        array2         []int

        x              int

       // suma           int = 0

    )

    fmt.Scanln(&cases)

    for i := 0; i < cases; i++ {

        fmt.Scanln(&couples)

        array = nil

        for j := 0; j < couples; j++ {

            fmt.Scanf("%d ", &x)

            array = append(array, x)

        }

        fmt.Println(array)

        array2 = nil

        for j := 0; j < couples; j++ {

            //fmt.Println("flag")

            fmt.Scanf("%d ", &x)

            array2 = append(array2, x)

            //suma += 0

        }

        fmt.Println(array2)

    }

}

I would use strings package - strings - pkg.go.dev and strconv package - strconv - pkg.go.dev. This shows how to read line by line Read a file (stdin) line by line · YourBasic Go

1 Like

Hey, thank you for replying,I already solved it, had to use bufio.scanner, string.split and strconv.Atoi. Solved the thing but I’m still wondering why the error happens, I’m gonna try to find out for now on.

Don’t ignore the error returned from Scanx. It may provide a clue.