Input Validation for only integers?


I created a program that will calculate the factorial of the number entered and am having a hard time getting it to not accept decimals or fractions.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;
int main (){
	
	int number = 0;
		
	cout<<"Please enter a positive whole number:"<<endl;
	while(!(cin>>number)||number<0){
		cin.clear();
		while(cin.get()!='\n'){ /*Also, this was the only thing I could find to stop it from looping Invalid 
                                        //input endlessly but I am not sure exactly what this is doing, if anyone
                                        //could explain that would help alot*/
			continue;
			cin>>number;
		}
		cout<<"Invalid Input"<<endl;
		}
	int x = number;	
	int y=1;
	while(x>1){
		y = y*x;
		x--;
		}
	cout<<y;
	return 0;
}




I am 2 months into my first programming class ever and I cant seem to figure out how to get around the fact that if I enter '3.2' or '3/2' it will only look at the '3' and not the '.2', or '/2'. I would probably need to change the data type to float or something but then I am not sure how to use the input validation after that. I tried using isdigit(number) but that was not working either...and to be honest I may not have been using it right.

I have googled just about everything I could think of but I am not sure where to go. If anyone can point me in the right direction that would help immensely! Thanks!
Chuck
Last edited on
closed account (DSLq5Di1)
Replace your while loop with,

1
2
3
4
5
6
7
while ((cin >> number).fail() || cin.peek() != '\n' || number < 0)
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    cout << "Invalid Input\n";
}
Thanks!
I put in the code above and it didn't work (undeclared numeric_limits), but I was able to add the cin.peek() != '\n' to my while statement and it works now... the only thing is, I have no clue what that does. Can anyone point me to a good place to learn about these cin.clear/peek/get and the like, or if you have the time, explain what they are doing in this loop?

Thanks again,
Chuck
closed account (DSLq5Di1)
Oh sorry, forgot to mention you need #include <limits> .

peek() returns the next character in the stream without extracting it, clear() is used to reset the stream state (ie. if a failed extraction occurs), get() extracts a character from the stream.

See http://www.cplusplus.com/reference/iostream/istream/ for a reference of what you can do with cin.
Topic archived. No new replies allowed.