Only accept positive integers

I need this to only accept positive integers. so if I enter a negative or something with a decimal it won't take it. This is what I have now. I just need help where it won't take it if it isn't an integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdlib>
#include <cassert> 
using namespace std;

int main ( )
{
	int N;
	
	do 
	{
	
		cout << endl << "Please enter a positive integer : " ;
		cin >> N ;
	if( N < 0 || N % 0 != 0 ) //
		assert ( N % 0 != 0 );
        cout << "Invalid number." << endl;
	}
	while( N < 0 || N % 0 != 0 ); // 
N will always be an integer. If you try to enter a number with a decimal point, the decimal point and anything after it will be ignored.
Ohhhh! Thank You!
If you want to avoid negatives and throw out stuff like people typing in strings, try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <limits>

int main()
{
    int input;
    while(std::cout << "Enter a positive integer: " &&
          (!(std::cin >> input) || input < 0))
    {
        std::cout << "Not a positive integer!\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    //do stuff with input
    return 0;
}


This basically says, "As long as I can print this prompt, and you type something that puts cin in a fail state, or you give me an integer less than 0, I'm throwing it out and asking you again."
Last edited on
Or you could use cire's approach, for even better robustness:
http://www.cplusplus.com/forum/beginner/108849/#msg592118

The clear/ignore approach booradley60 suggests will accept strings which begin with a valid number but continue on with other chars. e.g.

42nd Street -> 42
99 red balloons -> 99
3.14 -> 3
1 2 3 4 -> 1

cire's approach ensure that the input is just a number, with optional predicate.

Andy
The clear/ignore approach booradley60 suggests will accept strings which begin with a valid number but continue on with other chars. e.g.


What do you mean? The type int does that without any help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# include <iostream>
using namespace std;

int main()
{         
    int x; 
	
    cout << "Enter a number: ";
    cin >> x;
	
    cout << "You entered " << x << '\n';

    system("pause");
    
    return 0;
}


This doesn't check for a positive number and gives trash if it doesn't start with a number, but it will give the same results for the input you used.
@admkrk
That's his point. What if you were using a file stream instead of cin, you would WANT to have 42nd Street be a failure if you were expecting an int field (probably indicates a malformed file), not just accept the integer.

My only problem with cire's code is that I have not done anything to bone up on C++11, so the predicate part of his code is difficult for me to read.

EDIT (clarification): I am supporting andywestken's suggestion over mine, and this post was intended as a response to admkrk. :)
Last edited on
That's what Andy was saying yours allows for junk to be inputted. Where as cires approach does not allow junk.

basically the OP probably doesn't want someone to input 1.23 for 1 he wants 1 for 1. So yeah ints truncate everything but the value entered is still not valid.
I didn't consider a file stream and cin was used in the example. I also left off error checking because I didn't know how involved Joshcannon wanted to get with it. cire's approach certainly covers most if not all the possibilities, but it is most likely overkill and unusable for someone in a class and having this kind of problem.

While my answer isn't the best solution, I think it was more appropriate.

So yeah ints truncate everything but the value entered is still not valid.


I did expect a follow up asking about that by the way and I should have mentioned it originally, but since it seemed to have solved his problem the truncating might have been all that was needed.
Topic archived. No new replies allowed.