having problem with while loop

i am new in C++,My program is asking user to enter integer, and i want to show the error message when user enter anythings expect integer.But i have a problem,whenever i enter the world first, it just terminate the program.
for example, i enter "sad", it shows "integer only" and then end of program.However, if i enter integer in first try, it works fine, even though i enter world in second and so on, it works perfectly.In addition, can anyone explains the cin.clear and cin.ignore. i just copy them online.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>
#include <limits>
using namespace std;

int main() {
	int a;
	while(true){
		cout << "Enter a integer greater than 666: ";
	cin >> a;
	
	if(!cin) {
		cout << "integer only\n";
	cin.clear();
	cin.ignore(numeric_limits<int>::max(), '\n');
	}
	if (a < 666) return 0;
	if ((a % 10 + a % 100 / 10) == 13) cout << "Evil\n";
	} 
	return 0;
}
It looks like the program exits due to this line:

 
if (a < 666) return 0;

Try printing the value of variable a before and after the if(a < 666) check (line 16). You'll find that it holds a junk value. This happens because a was not initialized and the attempt to assign a value on line 9 fails when the user enters a word.

When you enter an valid integer first, a gets an valid value. Your loop continues as long as a remains valid. Later attempts to change the value to "sad" fail, so it keeps the original value you assigned it.

From what I've learned so far, a common way to validate input is to include the cin operation within a conditional statement. For example:

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

int main() {
	int a;

	cout << "enter an integer: ";
	while (!(cin >> a))  // (cin >> a) == true if assignment successful
	{
		cout << "invalid input, please enter an integer: ";
		cin.clear();
		cin.ignore(numeric_limits<int>::max(), '\n');
	}

	cout << "thank you. your integer is " << a << '\n';

	return 0;
}


cin has internal flags that indicate it's status. If an attempt to read in fails for some reason, some of those flags are switched to indicate that cin didn't work. This applies to other input/output streams too, such an ifstream for reading from files.

To reset those flags, we can use cin.clear(). This lets us use cin again. It's possible that there's still characters in the stream, however, so we can use cin.ignore() to discard any lingering input.
Last edited on
Topic archived. No new replies allowed.