问题
Testing cin for non numeric, non zero,and non negative values and entering loop. Cannot see why the test for values <=0 portion is not working. it should output:
cout << "Invalid value input\n";
Thanks in advance for catching what is probably a silly error.
#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;
}
回答1:
It's not working because of unsigned int integer;
.
Changing this to int integer to check for negative verification.
Range of the value of an unsigned int is 0 to 4,294,967,295 (4 bytes)
So -1 in unsigned means 4,294,967,295 as -1 bit representation is 111~11 (32 Ones)
You may check 2's Complement for binary bit subtraction and how -1 became 2^32-1
来源:https://stackoverflow.com/questions/58476766/c-negative-verification-is-not-working