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>
usingnamespace 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 ); //
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."
@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. :)
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.