英文:
Golang: the hang of fmt.Printf stdout happened next to fmt.Scan stdin in the for loop
问题
标题上说,我很难描述这个问题。所以我展示了下面的示例代码、输入和输出。
package main
import (
"fmt"
)
func main() {
for i := 1; i <= 3; i++ {
var a, b, c string
fmt.Scan(&a)
fmt.Scan(&b)
fmt.Scan(&c)
fmt.Printf("%s\n", a)
}
}
输入:
a b c
d e f
g h i
期望输出:
a
d
g
然而,实际输出先打印了"a"和"d"。然后,在按下回车键后,打印了"g"。这是实际输出。
更新
如果我粘贴了全部九个字符,第三次迭代就会卡住。
然而,如果我仅仅逐个输入字符,它就符合预期的输出。
英文:
As title, it's hard for me to describe the problem. So I showed the sample code, input and output below.
package main
import (
"fmt"
)
func main() {
for i := 1; i <= 3; i++ {
var a, b, c string
fmt.Scan(&a)
fmt.Scan(&b)
fmt.Scan(&c)
fmt.Printf("%s\n", a)
}
}
Input
a b c
d e f
g h i
Expected Output
a
d
g
However, the actual output printed "a", "d" first. Then, after pressing return (enter) key, "g" was printed. This was actual output.
Update
If I pasted whole nine characters, the third iteration was hung.
However, if I merely enter character one after another, it met the expected output.
答案1
得分: 2
你是如何在没有**回车(Enter)**的情况下输入这个输入的?
如果你在交互式环境中运行并且实际键入所有的输入,我想你会理解输出结果的原因。
你需要:
- 输入
a b c
- 目前还没有输出,因为第三个Scan
不知道c
是否是你要输入的全部内容 - 按下
回车(Enter)
- 只有在这一点上你才会看到a
的输出 - 对其他行也是同样的操作
查看一下Scan
的文档,它也解释了这一点:
https://golang.org/pkg/fmt/#Scan
英文:
How did you enter that input without a return (enter) ?
If you run this interactively and actually typing in all the input I think you'll understand the reason for the output.
You will have to:
- Type
a b c
- nothing will output yet as the thirdScan
does not know ifc
is all you'll type - Press
return (enter)
- only at this point you'll see thea
output - Do the same for the other lines
Take a look at the doc for Scan
which explains this as well:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论