英文:
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
也许你只想逐行读取一个纯文本文件?
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?
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论