C ++(负验证不起作用)>

问题描述 投票:0回答:1

测试cin是否为非数值,非零和非负值,然后进入循环。无法看到为什么对值<= 0的测试不起作用。它应该输出:

cout << "Invalid value input\n";

感谢您捕捉可能是一个愚蠢的错误。

#include <iostream>
using namespace std;

int main()
{
    unsigned int integer;

    cout<< "Enter a non negative number greater than 0: ";
    cin>> integer;

    do
    {
         while(!cin || integer <= 0)//validation condition
         {
             cout << "Invalid value input\n";
             cin.clear();
             cin.ignore(200, '\n');
             cout<< "Enter a non negative number greater than 0: ";
             cin>> integer;
         }
         cout<< "Enter a non negative number greater than 0: ";
         cin>> integer;
    } while(integer !=1);

    return 0;
}

测试cin是否为非数值,非零和非负值,然后进入循环。无法看到为什么对值<= 0的测试不起作用。它应该输出:cout <

由于unsigned int integer;而无法正常工作。将此值更改为int整数以检查否定验证。无符号int值的范围是0到4,294,967,295(4个字节)因此-1的无符号表示4,294,967,295,因为-1位表示为111〜11(32位)您可以检查2's Complement以进行二进制减法,并且-1变成2 ^ 32-1的方式

c++ do-while verification
1个回答
0
投票

由于unsigned int integer;而无法正常工作。将此值更改为int整数以检查否定验证。无符号int值的范围是0到4,294,967,295(4个字节)因此-1的无符号表示4,294,967,295,因为-1位表示为111〜11(32位)您可以检查2's Complement以进行二进制减法,并且-1变成2 ^ 32-1的方式

© www.soinside.com 2019 - 2024. All rights reserved.