c++ - 使用 isdigit 通知任何检测到的非法字符
问题描述
我在使用 isdigit 时遇到问题
#include <iostream>
using namespace std;
int main() {
int x = 0;
int y = 1;
int ndCount[10];
for (x = 0; x < 10; x++,y++) {
cout << y << ". Enter a whole number: ";
cin >> ndCount[x];
if (!isdigit(ndCount[x])) {
cout << "Error, Please try again \n";
}
}
return 0;
}
每当我尝试输入一个数字时,它仍然会注册为“错误请重试”。另外,当我尝试使用字符时,它会自动出错
解决方案
要检查用户是否输入了有效数字,请执行以下操作:
if(!(cin >> ndCount[x]))
throw std::runtime_error("not a number");
operator>>
failbit
无法解析值时的流集。然后operator!
检查是否failbit
已设置。
推荐阅读
- objective-c - CLS_LOG 应该放在崩溃之前还是之后?无论哪种方式,它都不会记录数据
- kotlin - 如何从数组中获取每个项目?
- ios - 将多个 AVAudioSequencer 与一个或多个 AVAudioUnitSampler 一起使用
- javascript - 只有部分音频播放器有效
- node.js - 无法使用 mongoose 通过 node.js 连接到 mongoDB
- php - 汇总具有相同类别的字符串中的数字
- java - 我需要做一个加入购物车的功能(饮料应用程序)
- excel - 如果在 D 列或 E 列中找到标记/突出显示,则从 C 列的每个单元格中搜索 D 列的每个单元格中的字母数字值
- html - 如何使画布标签的宽度与窗口的一半一样大?
- json - 如何从响应中获取令牌?