英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论