1 回答
TA贡献1830条经验 获得超9个赞
最简单的方法是按行循环遍历文件。像这样的东西:
package main
import (
"bufio"
"fmt"
"log"
"strconv"
"strings"
)
type Student struct {
FirstName string
LastName string
}
func main() {
fmt.Println("What is the name of your file?\n") var filename string
fmt.Scan(&filename)
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 {
// skip blank lines
continue
}
if '0' <= line[0] && line[0] <= '9' {
sum := 0
for _, field := range strings.Fields(line) {
n, err := strconv.Atoi(field)
if err != nil {
log.Fatal(err)
}
sum += n
}
fmt.Println(sum)
} else {
fields := strings.Fields(line)
if len(fields) != 2 {
log.Fatal("don't know how to get first name last name")
}
fmt.Println("First:", fields[0], "Last:", fields[1])
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
- 1 回答
- 0 关注
- 135 浏览
添加回答
举报