问题描述
代码:
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)
Golang 的完全初学者.我试图解决 r/dailyprogrammer 的问题之一.我用代码片段读取来自 SO 的输入以及 strconv.Atoi 函数.这个函数的例子很有意义,但是当我将它应用到从 stdin 读取的输入时,它给了我 0.
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.
推荐答案
如果您稍微更改代码,您会看到 strconv.Atoi(input)
返回错误.我希望您现在已经学到了关于 Go 如何处理错误的重要一课.
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.
错误是:strconv.Atoi:解析1\n":语法无效
out, err := strconv.Atoi(input)
if err != nil {
fmt.Printf("Error is: %v\n", err)
}
解决此问题的一种方法是使用 strings.TrimSuffix 修剪 input
():
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)
您还可以使用 扫描仪,它不需要您删除\n
:
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()
这篇关于从 stdin 读取的字符串类型转换为 int 给我一个 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!