0

I have a txt file :

2
Data 5 1.32
DataSecond 4 5.41
4
...

And so on. How to read the first line to know the count and then go on spliting the other lines to get individual parameters? I tried doing as follows, but it is obviously wrong.

f, err := os.Open("DATA.txt")
check(err)
s := bufio.NewScanner(f)
for s.Scan() {
    line := s.Text()
    count, err := strconv.Atoi(line)
    check(err)
    for i := 0; i < count; i++ {
        testArray := strings.Fields(s.Text())
        for _, v := range testArray {
            fmt.Println(v)
        }
    }
}
1

2 Answers 2

1

You just forgot to Scan() inside the inner loop.

f, err := os.Open("DATA.txt")
check(err)
s := bufio.NewScanner(f)
for s.Scan() {
    line := s.Text()
    count, err := strconv.Atoi(line)
    check(err)
    for i := 0; i < count && s.Scan(); i++ {
        testArray := strings.Fields(s.Text())
        for _, v := range testArray {
            fmt.Println(v)
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could do something like this, read the single lines into a count int and use it as a test. If count is > 0 then use sscanf to get the other values

func main() {
    f, err := os.Open("DATA.txt")
    check(err)
    s := bufio.NewScanner(f)
    count := 0
    for s.Scan() {
        line := s.Text()
        if count < 1 {
            count, err = strconv.Atoi(line)
            check(err)
            continue
        }
        count--
        var tag string
        var n int
        var f float64
        fmt.Sscanf(line, "%s %d %f", &tag, &n, &f)
        // not sure what you really wnant to do with the data!
        fmt.Println(n, f, tag)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.