C++中的整数验证

  • 本文关键字:验证 整数 C++ c++
  • 更新时间 :
  • 英文 :


亲爱的程序员们,你好,我正在用 c++ 编写一个系统,我有一段时间远离这种语言,我定义了一个函数,其中将询问一组问题以获取特定数据,因此输入与验证一起进行,当我想验证一个整数以检查输入的值是否只是数字时, 不知何故它不起作用,我写了一个函数"isnumber"来检查值是否为数字,但不知何故,即使我输入数字,它也会转到我的 if 条件并找到没有数字。我希望我没有犯一个非常愚蠢的错误,但任何考虑都是值得赞赏的。这是代码;

// validation Against Numbers 
bool isNumber(int a)
{
    if (isdigit(a)){
        return true;
    }
    else {
        return false;
    }
}

收集公寓详情

 cout << "Number Of Bedrooms:" << endl;
    cin >> number_of_bedrooms;
    if (isNumber(number_of_bedrooms) == false ) {
        cout << "Please Do Enter Numbers Only" << endl;
        cin.clear();
    }
    else if (number_of_bedrooms != '2' || number_of_bedrooms != '3' || number_of_bedrooms != '4') {
        cout << "The Number of Bedrooms Is Limited To 2, 3 or 4 !" << endl;
        cin.clear();
    }

在C++中,您可以取消isdigit调用,而是执行以下操作(未经测试):

int num;
if (std::cin >> num)
{
    // Read a number from cin
    std::cout << "Yay" << std::endl;
}
else
{
    // Grr
    std::cout << "failed to read number" << std::endl;
    std::cin.clear();  // Clears error state flags
}
C++运算符在

流中<<读取格式化的输入,因此它会将您输入的数字转换为整数,如果失败,则设置内部错误状态标志。

如果你不想使用 isdigit,你需要读取单个字符(因为 isdigit 接受单个字符/int 作为其参数):

char ch;
std::cin >> ch;
if (std::cin.good() && isdigit(ch))
{
    // Yay
}
即使在

读取单个字符时,仍然检查std::cin是否仍然良好也是一个好主意,因为调用仍然可能失败(也许用户发送了 EOF 信号)。

最新更新