1

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;
}
Knoep
  • 858
  • 6
  • 13
  • The would be a lot cleaner if you only had one set of the "enter a number", that is `do {` enter number, complain if bad `} while (` not 1 `);` . But if you want to make it work as is please explain exactly HOW it is not working. See [ask]. – Dave S Oct 20 '19 at 20:02
  • 3
    Are you entering negative numbers? Note that `unsigned int` cannot store negative values. Whether `cin` should fail on input of negative numbers for `unsigned` is discussed in [this question](https://stackoverflow.com/questions/49921271/should-reading-negative-into-unsigned-fail-via-stdcin-gcc-clang-disagree). – walnut Oct 20 '19 at 20:03
  • 3
    `integer` is `unsigned int`, meaning it can not have a negative value. So if you try to give it a negative value it will "wrap around" and get a positive value instead. If you want negative values you need to use `int integer;` – super Oct 20 '19 at 20:06
  • Thank you uneven_mark, That does the trick. I'll look into that thread for clarification on why it 'fails'. – Rachel Funball Oct 20 '19 at 20:11

1 Answers1

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

sabertooth
  • 582
  • 1
  • 7
  • 23