在解析文件中的每一行后,scanner.Text() 的类型是什么?

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

What is the type of scanner.Text() after parsing each line in a file?

问题

我目前正在阅读一个名为input.txt的文本文件,其中包含以下输入:

  1. 123
  2. 456
  3. 789

解析它的代码如下:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. file, err := os.Open("input.txt")
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. defer file.Close()
  13. scanner := bufio.NewScanner(file)
  14. count := 0
  15. var line string
  16. for scanner.Scan() {
  17. count += 1
  18. line = scanner.Text()
  19. fmt.Println(line)
  20. if line == "123" {
  21. fmt.Println("EQUAL")
  22. }
  23. }
  24. }

为什么文件的第一行与代码中硬编码的字符串123不匹配?

英文:

I am currently reading a text file input.txt with the following inputs:

  1. 123
  2. 456
  3. 789

The code to parse it is:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. file, err := os.Open("input.txt")
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. defer file.Close()
  13. scanner := bufio.NewScanner(file)
  14. count := 0
  15. var line string
  16. for scanner.Scan() {
  17. count += 1
  18. line = scanner.Text()
  19. fmt.Println(line)
  20. if line == "123" {
  21. fmt.Println("EQUAL")
  22. }
  23. }
  24. }

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.

huangapple
  • 本文由 发表于 2017年3月23日 22:13:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/42978596.html
匿名

发表评论

匿名网友

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

确定