fmt.Scanf does not do proper error checking

(Amjad Sayed) #1


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")


     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

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

My question is if I enter 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 (

func main() {
	var first, second float64

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

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

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

(Amjad Sayed) #4
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

(Lutz Horn) #7

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