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

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

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

问题

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

John
Marcus
Tom

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

英文:

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

John
Marcus
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:

John
Marcus
Tom

main.go:

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	file, err := os.Open("names.txt")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Println("name:", line)
		fmt.Println("length:", len(line))
	}
}

output:

name: John
length: 4
name: Marcus
length: 6
name: Tom
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:

John
Marcus
Tom

main.go:

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	file, err := os.Open("names.txt")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Println("name:", line)
		fmt.Println("length:", len(line))
	}
}

output:

name: John
length: 4
name: Marcus
length: 6
name: Tom
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:

确定