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
int main ( )
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 ); //
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. :)
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.