首页 > 解决方案 > 使用 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;
 }

每当我尝试输入一个数字时,它仍然会注册为“错误请重试”。另外,当我尝试使用字符时,它会自动出错

标签: c++

解决方案


要检查用户是否输入了有效数字,请执行以下操作:

if(!(cin >> ndCount[x]))
    throw std::runtime_error("not a number");

operator>>failbit无法解析值时的流集。然后operator!检查是否failbit已设置。


推荐阅读