dongtan7351 2019-02-24 09:10
浏览 82
已采纳

从stdin读取到int的字符串的类型转换给我0

Code:

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter a number")
input,_ := reader.ReadString('
')
fmt.Printf("Type of the entered value is %T
",input)
fmt.Println(input)
out,_ := strconv.Atoi(input)
fmt.Printf("Type now is: %T
", out)
fmt.Printf("Value now is %d
",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条回答 默认 最新

  • dongyi1429 2019-02-24 09:23
    关注

    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 ": invalid syntax

    out, err := strconv.Atoi(input)
    if err != nil {
        fmt.Printf("Error is: %v
    ", 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('
    ')
    input = strings.TrimSuffix(input, "
    ")
    fmt.Printf("Type of the entered value is %T
    ", input)
    fmt.Println(input)
    out, err := strconv.Atoi(input)
    if err != nil {
        fmt.Printf("Error is: %v
    ", err)
    }
    fmt.Printf("Type now is: %T
    ", out)
    fmt.Printf("Value now is %d
    ", out)
    fmt.Println(out)
    

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

    scanner := bufio.NewScanner(os.Stdin)
    fmt.Print("Enter a number")
    scanner.Scan()
    input := scanner.Text()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起