从 stdin 读取到 int 的字符串的类型转换给我一个 0
Type conversion of a string read from stdin to int is giving me a 0
代码:
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 函数。这个函数的例子很有意义,但是当我将它应用到我从标准输入读取的输入时,它给了我 0.
如果稍微更改一下代码,您会发现 strconv.Atoi(input)
正在返回错误。我希望您现在已经学到了关于 Go 如何进行错误处理的重要一课。
Error is: strconv.Atoi: parsing "1\n": invalid syntax
out, err := strconv.Atoi(input)
if err != nil {
fmt.Printf("Error is: %v\n", err)
}
解决此问题的一种方法是使用 strings.TrimSuffix() 修剪 input
:
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)
您也可以使用 Scanner,不需要您删除 \n
:
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter a number")
scanner.Scan()
input := scanner.Text()
代码:
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 函数。这个函数的例子很有意义,但是当我将它应用到我从标准输入读取的输入时,它给了我 0.
如果稍微更改一下代码,您会发现 strconv.Atoi(input)
正在返回错误。我希望您现在已经学到了关于 Go 如何进行错误处理的重要一课。
Error is: strconv.Atoi: parsing "1\n": invalid syntax
out, err := strconv.Atoi(input)
if err != nil {
fmt.Printf("Error is: %v\n", err)
}
解决此问题的一种方法是使用 strings.TrimSuffix() 修剪 input
:
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)
您也可以使用 Scanner,不需要您删除 \n
:
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter a number")
scanner.Scan()
input := scanner.Text()