1

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("\nPlease enter a valid number: ")
        }
    }
}

I would like to modify this to read two floating point numbers for e.g.

func main() {
    fmt.Print("\nEnter 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.

ain
  • 22,394
  • 3
  • 54
  • 74
r_duck
  • 149
  • 6

2 Answers2

3

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\n", a, b)
    }

}

output:

Got 1.000000, 2.000000
Got 0.100000, 0.200000
Got 1.234000, 2.234000

https://play.golang.org/p/7ATyjlkPhnD

Slabgorb
  • 786
  • 6
  • 17
  • this code is simpler-ish, but @lutz-horn 's answer below would handle user input including spaces, whatever a bit better (could strings.Trim the parts, for instance) – Slabgorb May 03 '18 at 14:48
1

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("\nPlease enter a valid number: ")
        }
        y, err := strconv.ParseFloat(parts[1], 64)
        if err != nil {
            fmt.Println("ERROR:", err)
            fmt.Print("\nPlease enter a valid number: ")
        }
        return x, y
    }
}

func main() {
    fmt.Print("\nEnter 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