fmt.Scanf does not do proper error checking

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?

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

Also, both 4.5 and 6.6 are no integers.

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

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

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

1 Like

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

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

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.