英文:
What is the type of scanner.Text() after parsing each line in a file?
问题
我目前正在阅读一个名为input.txt
的文本文件,其中包含以下输入:
123
456
789
解析它的代码如下:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("input.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
count := 0
var line string
for scanner.Scan() {
count += 1
line = scanner.Text()
fmt.Println(line)
if line == "123" {
fmt.Println("EQUAL")
}
}
}
为什么文件的第一行与代码中硬编码的字符串123
不匹配?
英文:
I am currently reading a text file input.txt
with the following inputs:
123
456
789
The code to parse it is:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("input.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
count := 0
var line string
for scanner.Scan() {
count += 1
line = scanner.Text()
fmt.Println(line)
if line == "123" {
fmt.Println("EQUAL")
}
}
}
Why does the first line of the file not match the hard coded string 123
in the code?
答案1
得分: 2
根据评论中提到的,这是由文件中的特殊字符引起的。在这种情况下,可能是UTF-8的BOM,也可能是DOS格式的\r
,或者其他不可打印字符。
英文:
As mentioned in the comments, this is due to special characters in the file. In this case the utf8 bom, but could be dos format \r
, or other non-printable characters.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论