Best code to prevent negative numbers?

Hello, I went back to this old code that I wrote for fun. I realized that while invalid input is blocked, I never put in code that prevents entering negative numbers. What is the most optimal way of integrating a "if(nAge < 0)" check in this existing code. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <limits>

using namespace std;

int main(int nNumberArgs, char* pszArgs[])
{
    string sAge;
    int nAge = 0;
    while(cout << "Enter an age for the creature: " << endl
          && !(cin >> nAge))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "ERROR: Illegal input!" << endl;
    }
    
    // ...rest of code omitted for brevity

    return 0;
}
change nAge from int to unsigned.
If you want the same error message to be shown when entering a negative number you could just add the check to the loop condition.
1
2
3
    while(cout << "Enter an age for the creature: " << endl
          && !(cin >> nAge)
          && nAge < 0)
dhayden wrote:
change nAge from int to unsigned.

I also thought about that but when I tested it with GCC it didn't work.
https://ideone.com/y4koR7
Thank you all, I got the code working. I used peter87's solution, but had to put || instead of &&.

1
2
3
    while(cout << "Enter an age for the creature: " << endl
          && !(cin >> nAge)
          || nAge < 0)
Topic archived. No new replies allowed.