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

半世苍凉 提交于 2021-01-29 08:25:24

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/54850390/type-conversion-of-a-string-read-from-stdin-to-int-is-giving-me-a-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!