C++ (negative verification is not working

十年热恋 提交于 2019-12-08 04:33:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!