fmt.Scanf does not do proper error checking


(Amjad Sayed) #1

Hello

I am new to golang. I am testing on Version 1.11.8
I am trying to read a float and error checking.

/// var first float64
///_,err = fmt.Scanf("%f", &first)
// if err != nil {
// fmt.Printf("%f is not a valid float")

///}

_,err2 := fmt.Scanf("%f", &second)

   if err2 != nil {
      fmt.Println("second number is not a valid numnber , exiting the program")

os.Exit(1)
}

     sum := first + second
     fmt.Printf("Sum of %f and %f is %f" , first,second ,sum)

}

When I execute this program as follows ,. I get the following error
Please enter the first integer
4.5.6.6

Please enter the second integer
Sum of 4.500000 and 6.600000 is 11.100000

My question is if I enter 4.5.5.6 why does it not generate an error message . Are the dots taken as newline?


(Lutz Horn) #2

Is this really your input? Why are there three dots?

Also, both 4.5 and 6.6 are no integers.


(Lutz Horn) #3

Try this:

package main

import (
	"fmt"
	"os"
)

func main() {
	var first, second float64

	fmt.Printf("first: ")
	_, err := fmt.Scanf("%f", &first)
	if err != nil {
		os.Exit(1)
	}

	fmt.Printf("second: ")
	_, err = fmt.Scanf("%f", &second)
	if err != nil {
		os.Exit(1)
	}

	sum := first + second
	fmt.Printf("Sum of %f and %f is %f", first, second, sum)
}

https://play.golang.com/p/Zcdln63c5Zf


(Amjad Sayed) #4

https://pastebin.com/eCBWLxyf
Still same thing, Why does it not crash when I put in 3 dots instead of one dot?


(Lutz Horn) #5

Why on earth do you want to put three dots into a float? That makes no sense.


(Amjad Sayed) #6

Ok, let the variables be integer and then when you enter input put it as float, should it not exit the program

https://pastebin.com/Dr04Q93n


(Lutz Horn) #7

Take a look at the documentation of scanning. It describes hwo fmt.Scanf works.