我想逐个字符读取文本文件,并打印那些超过"H"的字符和超过"8"的数字的无效输入。我的输入是
I9,A2
A10,C3
D2,L3
输出:所有三个的无效输入
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func main() {
lines, err := readLines("chessin.txt")
if err != nil {
log.Fatalf("readLines: %s", err)
}
var numLines int = len(lines)
for i := 0; i < numLines; i++ {
for j := 0; j < len(lines[i]); j++ {
if j > 'H' {
fmt.Printf("invalid input")
}
}
}
}
您需要编辑内部循环来检查每个输入行,
然后找到数字,然后逗号等等,就像这个工作示例代码:
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func checkOne(letter byte, number, i, j int) {
if letter > 'H' {
fmt.Printf("invalid input %q @ (%d, %d) n", letter, i, j)
}
if number > 8 {
fmt.Printf("invalid input number %d @ (%d, %d) n", number, i, j+1)
}
}
func main() {
lines, err := readLines("chessin.txt")
if err != nil {
log.Fatalf("readLines: %s", err)
}
var numLines int = len(lines)
for i := 0; i < numLines; i++ {
line := lines[i]
j := 0
comma := strings.IndexByte(line, ',')
if comma == -1 {
log.Fatalf("comma not found at line: %d", i)
}
number, err := strconv.Atoi(line[j+1 : comma])
if err != nil {
log.Fatalf("line:%d err: %s", i, err)
}
checkOne(line[j], number, i, j)
j = comma + 1
number, err = strconv.Atoi(line[j+1:])
if err != nil {
log.Fatalf("line:%d err: %s", i, err)
}
checkOne(line[j], number, i, j)
}
}
输入文件"chessin.txt":
I9,A2
A10,C3
D2,L3
输出:
invalid input 'I' @ (0, 0)
invalid input number 9 @ (0, 1)
invalid input number 10 @ (1, 1)
invalid input 'L' @ (2, 3)
您可以通过使用字符串拆分和切片来简化。不要读取并存储数组中的所有值,然后再次循环使用它们。假设第一个字符总是大写,并且不会有负值。工作示例代码如下:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
file, err := os.Open("chessin.txt")
if err != nil {
fmt.Println(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
valid := []bool{}
for scanner.Scan() {
strs := strings.Split(scanner.Text(), ",")
valid = append(valid, validateStrings(strs))
}
fmt.Println(valid)
}
func validateStrings(strs []string) bool {
for _, str := range strs {
char := str[0]
num, err := strconv.Atoi(string(str[1:len(str)]))
if err != nil {
fmt.Println("Invalid input")
os.Exit(1)
}
if char < 'A' || char > 'H' || num > 8 || num < 0 {
return false
}
}
return true
}