im super new in golang_coding, i like to read a file and get printed out each 3 lines,
i googling it for a week can’t find the exact way how to do it.
vm: 2020
group vmMemcache
state started
vm: 2021
group vmMemcache
state started
vm: 2022
group haMemcache
state started
vm: 2023
group vmMemcache
state started
i googling it for a week can’t find the exact way how to do it.
Googling for an algorithm is not always helpful. Think about what you would do if you were the computer, and try to turn that into code.
You already have the code to read each line of the file in turn: scanner.Text() is the last read line of text. You want to store those lines until you have three of them, and then do “something” with the three lines. Then you ignore the blank line and start looking for another three lines.
One way of doing this is to collect lines into a slice, and do something when the slice is of length three.
scanner := bufio.NewScanner(f)
lines := []string{} // for storing the lines as they are read
for scanner.Scan() {
lines = append(lines, scanner.Text()) // add the new line to the stored lines
if len(lines) == 3 { // this is what we want, 3 lines read
// do something with the three lines
fmt.Println("Got three lines:")
for i, line := range lines {
fmt.Printf("Line %d is %s\n", i, line)
}
// -- end of doing something
lines = []string{} // reset the stored lines, ready for next block of 3
scanner.Scan() // skip the blank line
}
}
The output of this on your file is:
Got three lines:
Line 0 is vm: 2020
Line 1 is group vmMemcache
Line 2 is state started
Got three lines:
Line 0 is vm: 2021
Line 1 is group vmMemcache
Line 2 is state started
Got three lines:
Line 0 is vm: 2022
Line 1 is group haMemcache
Line 2 is state started
Got three lines:
Line 0 is vm: 2023
Line 1 is group vmMemcache
Line 2 is state started
@pcl thank you so much ! i have this printouts now.
❯ go run exer1.go
Got three lines:
Line 0 is vm: 8001
Line 1 is group haMemcache
Line 2 is state started
i had to put break at the end of your code… to choose the first three lines 0, 1, 2
im figuring out now how to manipulate it like how to printout, each of every three lines that i Need…