Understanding the fmt package in go

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

Understanding the fmt package in go

问题

输出中的2是从哪里来的?

我写了一个从标准输入读取值并将结果返回到标准输出的程序。

package main

import "fmt"

func main() {
    var steps, i, a, b int
    fmt.Scanf("%d", &steps)
    for i = 0; i <= steps; i++ {
        fmt.Scanf("%d", &a)
        fmt.Scanf("%d", &b)
        fmt.Println(a + b)
    }
}

我有一个输入文件:

2
2 5
4           8

当我用go run program.go < input运行程序时,我得到的输出是:

2
7
12

而不是:

7
12

为什么会这样?

英文:

Where comes the 2 from in the output ?

I wrote a program that reads from STDIN and return values to STDOUT.

package main

import &quot;fmt&quot;

func main() {
    var steps, i, a, b int
    fmt.Scanf(&quot;%d&quot;, &amp;steps)
    for i = 0; i &lt;= steps; i++ {
        fmt.Scanf(&quot;%d&quot;, &amp;a)
        fmt.Scanf(&quot;%d&quot;, &amp;b)
        fmt.Println(a + b)
    }
}

I have a input file

2
2 5
4           8

When I run the program with go run program.go &lt; input I get:

2
7
12

Instead of:

7
12

Why ?

答案1

得分: 3

在尝试后,结果发现(在我的Linux机器上),如果输入文件是以“Windows格式”(即CRLF行尾)保存的,它会出现你所描述的行为。如果输入文件是以“Unix格式”(即LF行尾)保存的,它会按预期工作。如果在行尾添加垃圾字符,例如:

2x
2 5x
4           8x

你也会得到相同的行为。所以看起来它不将CR识别为空白字符,无法被“%d”格式说明符跳过,并且在找到CR时停止读取,就像上面的示例中的x一样。

我认为这应该被称为一个bug。这确实很不方便,因为在Linux上处理文本文件时,遇到具有Windows风格行尾的文件并不罕见。

英文:

After having tried it, it turns out that (on my Linux machine) if the input file is in "Windows format", with CRLF line ends, it will give your behaviour. If the input file is in "Unix format, with LF line ends, it works as expected. You also get the same behaviour if you add garbage at the end of the lines, for example like this:

2x
2 5x
4           8x

So it seems that it doesn't recognise CR as a whitespace character, which can be skipped by the "%d" format specifier, and stops reading when it finds it, like it does with the x in my example above.

I think this should be called a bug. It certainly is inconvenient, since it isn't uncommon to encounter text files that happen to have Windows-style line ends when working on Linux.

答案2

得分: 0

"i <= steps" 应该改为 "i < steps"。

英文:

i &lt;= steps should be i &lt; steps.

huangapple
  • 本文由 发表于 2014年12月27日 18:14:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/27666260.html
匿名

发表评论

匿名网友

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

确定