关于 c :Catch cin 异常 | 珊瑚贝

Catch cin exception


我想询问用户输入,我用 cin 得到这样的输入

1
2
3
4
5
6
7
8
9
void AskForGroundstate() {
    cout <<“Please enter an groundstate potential value in Volt:” << endl;
    if (!(cin >> _VGroundstate)) {
        cin.clear();
        cin.ignore();
        cout <<“Groundstate potential not valid.” << endl;
        AskForGroundstate();
    }
}

_VGroundstate 是一个双精度值,所以如果用户输入一个没有数字的字符串,它应该再次要求他更好地输入。但问题是,当输入例如 “AA” 时,程序会执行 AskForGroundstate 两次,执行 “AAA” 三次等。我是否使用了 clear 错误?

  • 这不是问题,但是以下划线开头的名称后跟大写字母 (_Vgroundstate) 和包含两个下划线的名称保留供实现使用。不要使用它们。


问题是 cin.ignore() 丢了一个字符;您想将所有字符放到行尾:

1
2
cin.ignore(std::numeric_limits<std::streamsize>::max(), \
);

这可确保在最终用户再次提示输入之前删除所有无效输入。

  • Clion 说,无法解析容器 numeric_limits 吗?
  • @LucaThiede,与标准库中的其他所有内容一样,您必须包含其标头 <limits>。
  • @LucaThiede 您需要包含 <limits> 标头。


来源:https://www.codenong.com/38200600/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8705.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?