输入不被 fmt.Scanf 或 fmt.Scanln 接收

huangapple go评论80阅读模式
英文:

Input not taken by fmt.Scanf or fmt.Scanln

问题

我一直在尝试编写一个程序,该程序从用户那里接收整数输入并执行一些计算。问题是,每隔一次,程序会在没有接收任何输入的情况下提前结束。无论是使用Scanf还是Scanln,都会出现相同的行为。

相关的代码如下:

func main() {
	var N int
	var output []int
	fmt.Println("输入测试用例")
    //这一行只有在每隔一次时才执行
	fmt.Scanf("%d", &N)
	testCases(N, N, output)
}

它会打印出"输入测试用例"这一行,然后程序终止。但是当我再次运行程序时,它会继续执行。这个模式在每次尝试运行程序时都会重复出现。

英文:

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.

答案1

得分: 2

更好的做法是使用bufio包,它实现了带缓冲的I/O。scanf/scanln是无缓冲的。

scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
input := scanner.Text()
英文:

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

scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
input := scanner.Text()

huangapple
  • 本文由 发表于 2021年10月31日 17:23:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/69785464.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定