wrong input

hello,

i have a simple Q , for example if i ask a user to input an integer value, but instead of this he/she input a charecter value

i want to show that his/her input is wrong and shou input an integer

can anyboy show me how to fo this but please in a simple way?

just to understand

i have this code but i can't understand so i prefer to have a very simple code to understand and see how it works

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>  
using namespace std;  
  
bool cond;  
  
int main()  
{  
   int n;  
  
   do  
   {  
      cout << "Enter an integer number:";  
      cin >> n;  
  
      cond = cin.fail();  
  
      cin.clear();  
      cin.ignore(INT_MAX, '\n');  
  
   }while(cond);  
  
 return 0;  
}


waiting for you

The code you found is more eloquent but perhaps mine explains more. The cin input stream is a little tricky to do type checking with, so if you notice, both your example and mine use cin.fail() to check if the data types are correct. For more info check this thread: http://www.cplusplus.com/forum/beginner/2957/

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
27
28
29
int main()
{
	int num;
	bool valid = false;

	while (!valid)
	{
		valid = true; //Assume the cin will be an integer.

		cout << "Enter an integer value: " << endl;
		cin >> num;

		if(cin.fail()) //cin.fail() checks to see if the value in the cin
					//stream is the correct type, if not it returns true,
					//false otherwise.
		{
			cin.clear(); //This corrects the stream.
			cin.ignore(); //This skips the left over stream data.
			cout << "Please enter an Integer only." << endl;
			valid = false; //The cin was not an integer so try again.
		}

	}

	cout << "You entered: " << num << endl;

	system("PAUSE");
	return 0;
}


My apologies if I am incorrect about something, I'm still new as well and am not entirely familiar with the cin stream.
thanks it's very clear now
There is also this:
http://www.cplusplus.com/forum/beginner/13044/page1.html#msg62827
(for detecting user input like "4hello").
Topic archived. No new replies allowed.