dongzhuoxie1244 2015-03-17 10:36
浏览 69
已采纳

如何检查Scanln是否在Golang中引发错误

I am new to Go. I've been searching for answers and I know there really is one I just haven't found it.

To better explain my question, here is my code:

func main() {

    ...

    inputs := new(Inputs)

    fmt.Println("Input two numbers: ")

    fmt.Scanln(&inputs.A)
    fmt.Scanln(&inputs.B)

    fmt.Println("Sum is:", inputs.A + inputs.B)
}

And here is my struct:

type Inputs struct {
    A, B int
}

If I will input '123' for Input A and another '123' for Input B, I will have an output of "Sum is: 246". But if I will mistakenly input '123j' , it will no longer work since A and B accept int(s) only.

Now, how to catch the panic from fmt.Scanln or is there a way? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • douxiawei9318 2015-03-17 10:40
    关注

    Scanln returns values ... don't ignore them.

    You're ignoring two important return values. The count of the scan and an error .. if there was one.

    n, err := fmt.Scanln(&inputs.A)
    

    ...will give you what you need to check. err will tell you that a newline was expected and wasn't found .. because you've tried to store the value in an int .. and it errors when the last character in the available value isn't a newline.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计