How do I check to see how many bytes are left until EOL in Go?

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

How do I check to see how many bytes are left until EOL in Go?

问题

假设我有一个像这样的文件:

  1. John
  2. Marcus
  3. Tom

每个字符串都是由用户输入的,因此我不知道它们的大小。
我该如何编写一个函数来检查距离行尾(EOL)还有多少字节?

英文:

Let's say that I have a file like this:

  1. John
  2. Marcus
  3. Tom

Each of the strings are inputted by the user and therefore I do not know the size of them.
How would I make a function that would check how many bytes are left until the EOL?

答案1

得分: 2

也许你只想逐行读取一个纯文本文件? How do I check to see how many bytes are left until EOL in Go?

names.txt:

  1. John
  2. Marcus
  3. Tom

main.go:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. file, err := os.Open("names.txt")
  9. if err != nil {
  10. panic(err)
  11. }
  12. defer file.Close()
  13. scanner := bufio.NewScanner(file)
  14. for scanner.Scan() {
  15. line := scanner.Text()
  16. fmt.Println("name:", line)
  17. fmt.Println("length:", len(line))
  18. }
  19. }

output:

  1. name: John
  2. length: 4
  3. name: Marcus
  4. length: 6
  5. name: Tom
  6. length: 3
英文:

Maybe you just want to read a plain text file line by line? How do I check to see how many bytes are left until EOL in Go?

names.txt:

  1. John
  2. Marcus
  3. Tom

main.go:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. file, err := os.Open("names.txt")
  9. if err != nil {
  10. panic(err)
  11. }
  12. defer file.Close()
  13. scanner := bufio.NewScanner(file)
  14. for scanner.Scan() {
  15. line := scanner.Text()
  16. fmt.Println("name:", line)
  17. fmt.Println("length:", len(line))
  18. }
  19. }

output:

  1. name: John
  2. length: 4
  3. name: Marcus
  4. length: 6
  5. name: Tom
  6. length: 3

huangapple
  • 本文由 发表于 2022年7月22日 00:47:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/73069913.html
匿名

发表评论

匿名网友

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

确定