Mudit Jha
Mudit Jha

Reputation: 57

Type conversion of a string read from stdin to int is giving me a 0

Code:

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter a number")
input,_ := reader.ReadString('\n')
fmt.Printf("Type of the entered value is %T\n",input)
fmt.Println(input)
out,_ := strconv.Atoi(input)
fmt.Printf("Type now is: %T\n", out)
fmt.Printf("Value now is %d\n",out)
fmt.Println(out)

Complete beginner to Golang. I was trying to solve one of the problems from r/dailyprogrammer. I took the snippet to read the input from SO, as well as the strconv.Atoi function. The examples for this function make sense but when I apply it to the input I read from stdin, it gives me 0.

Upvotes: 1

Views: 1117

Answers (1)

Nic
Nic

Reputation: 12846

If you change your code a little you'll see that strconv.Atoi(input) is returning an error. I hope you've now learned an important lesson about how Go does error handling.

Error is: strconv.Atoi: parsing "1\n": invalid syntax

out, err := strconv.Atoi(input)
if err != nil {
    fmt.Printf("Error is: %v\n", err)
}

One way to fix this is by trimming input using strings.TrimSuffix():

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter a number")
input, _ := reader.ReadString('\n')
input = strings.TrimSuffix(input, "\n")
fmt.Printf("Type of the entered value is %T\n", input)
fmt.Println(input)
out, err := strconv.Atoi(input)
if err != nil {
    fmt.Printf("Error is: %v\n", err)
}
fmt.Printf("Type now is: %T\n", out)
fmt.Printf("Value now is %d\n", out)
fmt.Println(out)

You can also use the Scanner, which doesn't require you to remove the \n:

scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter a number")
scanner.Scan()
input := scanner.Text()

Upvotes: 5

Related Questions