This seems almost right but it chokes on the newline. What's the best way to do this?
package main
import (
"fmt"
"strings"
)
func main() {
var z float64
var a []float64
//
gives an error for Fscanf
s := "3.25 -12.6 33.7
3.47"
in := strings.NewReader(s)
for {
n, err := fmt.Fscanf(in, "%f", &z)
fmt.Println("n", n)
if err != nil {
break
}
a = append(a, z)
}
fmt.Println(a)
}
Output:
n 1
n 1
n 1
n 0
[3.25 -12.6 33.7]
Update:
See the answer from @Atom below. I found another way which is to break if the error is EOF, and otherwise just ignore it. It's just a hack, I know, but I control the source.
_, err := fmt.Fscanf(in, "%f", &z)
if err == os.EOF { break }
if err != nil { continue }
If you are parsing floats only, you can use fmt.Fscan(r io.Reader, a ...interface{})
instead of fmt.Fscanf(r io.Reader, format string, a ...interface{})
:
var z float64
...
n, err := fmt.Fscan(in, &z)
The difference between fmt.Fscan
and fmt.Fscanf
is that in the case of fmt.Fscan
newlines count as space. The latter function (with a format string) does not treat newlines as spaces and requires newlines in the input to match newlines in the format string.
The functions with a format string give more control over the form of input, such as when you need to scan %5f
or %10s
. In this case, if the input contains newlines and it implements the interface io.RuneScanner
you can use the method ReadRune
to peek the next character and optionally unread it with UnreadRune
if it isn't a space or a newline.
If your input is just a bunch of lines with floats separated by white space on each line, it might be easier to just read one line at a time from the file, run Sscanf on that line (assuming the number of floats on each line is fixed). But here's something that works in your example---there may be a way to make it more efficient.
package main
import (
"fmt"
"strings"
)
func main() {
var z float64
var a []float64
//
gives an error for Fscanf
s := "3.25 -12.6 33.7
3.47"
for _, line := range strings.Split(s, "
") {
in := strings.NewReader(line)
for {
n, err := fmt.Fscanf(in, "%f", &z)
fmt.Println("n", n)
if err != nil {
fmt.Printf("ERROR: %v
", err)
break
}
a = append(a, z)
}
}
fmt.Println(a)
}