C++ 使用isdigit通知任何检测到的非法字符
我使用isdigit有困难C++ 使用isdigit通知任何检测到的非法字符,c++,C++,我使用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(ndC
#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;
}
每当我尝试输入一个数字时,它仍然会注册为错误,请重试。
另外,当我尝试使用字符时,它会自动出错如果您将值存储在int中,则需要将其存储在char中,请尝试char ndCount[10] 这将检查您在控制台上输入的字符串上的每个数字
当然,如果要检查整数,则需要另一种方法。要检查用户输入的数字是否有效,请执行以下操作:
if(!(cin >> ndCount[x]))
throw std::runtime_error("not a number");
运算符>>在无法解析值时设置流的failbit。那么接线员!检查是否设置了故障位。isdigit用于检查字符。您正在检查int。