Home > database >  Input not taken by fmt.Scanf or fmt.Scanln
Input not taken by fmt.Scanf or fmt.Scanln

Time:11-01

I've been trying to write a program which takes in integer input from the user and performs some calculation. What's happening is that every alternate time, the program ends prematurely without having taken in any input. Both Scanf and Scanln follow the same behavior.

The relevant code:

func main() {
    var N int
    var output []int
    fmt.Println("Enter test cases")
    //This bottom line executes only every alternate time
    fmt.Scanf("%d", &N)
    testCases(N, N, output)
}

It prints the line "Enter test cases" and the program terminates. But when I run the program once more, it follows through. This pattern then repeats every time I try to run the program.

CodePudding user response:

Better use bufio package, it implements buffered I/O. scanf/scanln are unbuffered.

scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
input := scanner.Text()
  •  Tags:  
  • go
  • Related