doujie3888
2016-08-01 05:50 阅读 71
已采纳

从Golang文件中读取特定字符

I want to read a text file character by character and print invalid input for those characters that exceed "H"and numbers that exceed "8". eg: my input is

I9,A2
A10,C3
D2,L3

output: invalid input for all three

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")
            }
        }
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douliang1900 douliang1900 2016-08-01 07:15

    You need to edit the inner loop to check for every input line,
    and find the number then comma and so, like this working sample code:

    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) 
    ", letter, i, j)
        }
        if number > 8 {
            fmt.Printf("invalid input number %d @ (%d, %d) 
    ", 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)
        }
    }
    

    input file "chessin.txt":

    I9,A2
    A10,C3
    D2,L3
    

    output:

    invalid input 'I' @ (0, 0) 
    invalid input number 9 @ (0, 1) 
    invalid input number 10 @ (1, 1) 
    invalid input 'L' @ (2, 3) 
    
    点赞 评论 复制链接分享
  • dpp42324 dpp42324 2016-08-01 16:43

    You can simplify by using string split and slice. Do not read and store all the values in an array and then loop through them again. Assuming the first character is always Caps and there will be no negative values. Working sample code is as follows:

    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
    }
    
    点赞 评论 复制链接分享

相关推荐