Limiting entries to only positive non-decimal numbers

1
2
3
4
5
6
...
do
{
cin>>array[i];
}while(array[i]<0);
//Limits to only positive numbers 


What else should I write to make the user enter the number again if he types a decimal number. How do I add a message if the number is negative or decimal?

For example.

Enter number 1 -> -1
Negative number!
Enter number 1 -> 0.1
Decimal number!
Enter number 1 -> 2
Enter number 2 -> 3

Thank you very much for your help.
closed account (3qX21hU5)
The simple way to do it is this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
    int number;
    cin >> number;

    if (number < 0)
    {
        cout << "Your number is less then 0! Please enter a new number: ";
        cin >> number;

        if (number < 0)
            return -1;
    }

    cout << "Your number is: " << number << endl;
}


This is the simple way of doing things. If the user enters a negative number it prompts the user to enter a new number. He he enters one again it closes the program since the user is stupid ;p. There are far better ways to handle user errors and errors in general but this will give you a simple example.
Last edited on
Topic archived. No new replies allowed.