I have a function to read a single float64 from stdin:
func readFloat() float64 {
scanner := bufio.NewScanner(os.Stdin)
for {
scanner.Scan()
in := scanner.Text()
n, err := strconv.ParseFloat(in, 64)
if err == nil {
return n
} else {
fmt.Println("ERROR:", err)
fmt.Print("
Please enter a valid number: ")
}
}
}
I would like to modify this to read two floating point numbers for e.g.
func main() {
fmt.Print("
Enter x, y coordinates for point1: ")
x1, y1 := readFloat()
Problem I am facing is splitting scanner.Text()
. There is a function scanner.Split()
but cannot understand how to use it.
Any possible solutions would be helpful.
Use strings.Split
:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func readFloat() (float64, float64) {
scanner := bufio.NewScanner(os.Stdin)
for {
scanner.Scan()
in := scanner.Text()
parts := strings.Split(in, ",")
x, err := strconv.ParseFloat(parts[0], 64)
if err != nil {
fmt.Println("ERROR:", err)
fmt.Print("
Please enter a valid number: ")
}
y, err := strconv.ParseFloat(parts[1], 64)
if err != nil {
fmt.Println("ERROR:", err)
fmt.Print("
Please enter a valid number: ")
}
return x, y
}
}
func main() {
fmt.Print("
Enter x, y coordinates for point1: ")
x1, y1 := readFloat()
fmt.Println(x1, y1)
}
Using it:
$ go run main.go
Enter x, y coordinates for point1: 1.2,3.4
1.2 3.4
I would probably go with fmt.Sscanf
here
package main
import (
"fmt"
)
func main() {
testCases := []string{"1,2", "0.1,0.2", "1.234,2.234"}
var a, b float64
for _, s := range testCases {
_, err := fmt.Sscanf(s, "%f,%f", &a, &b)
if err != nil {
panic(err)
}
fmt.Printf("Got %f, %f
", a, b)
}
}
output:
Got 1.000000, 2.000000
Got 0.100000, 0.200000
Got 1.234000, 2.234000