Golang:在for循环中,fmt.Printf的标准输出紧跟在fmt.Scan的标准输入之后。

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

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 (
	&quot;fmt&quot;
)

func main() {
	for i := 1; i &lt;= 3; i++ {
		var a, b, c string
		fmt.Scan(&amp;a)
		fmt.Scan(&amp;b)
		fmt.Scan(&amp;c)
		fmt.Printf(&quot;%s\n&quot;, 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 third Scan does not know if c is all you'll type
  • Press return (enter) - only at this point you'll see the a output
  • Do the same for the other lines

Take a look at the doc for Scan which explains this as well:

https://golang.org/pkg/fmt/#Scan

huangapple
  • 本文由 发表于 2017年9月14日 23:55:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/46223589.html
匿名

发表评论

匿名网友

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

确定