!cin looping errors

Alright, so this is about avoiding erros when someone would enter a letter or something that isnt an integer. This work without crashing the program if you were to enter lets say a 'd'. But if I enter multiple nonintegers, lets say 'dddasdwa'. Then the program with loop the error message for as many letters were written. I was wondering if theres any fix for this. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>

using namespace std;

int main()
{
	int integer;

	cout << "Enter an integer: ";
	cin >> integer;
	cin.ignore();

	while (!cin)
	{
		cin.clear();
		cin.ignore();
		cout << "You must enter an integer.\nTry again: ";
		cin >> integer;
		cin.ignore();
	}
	cout << "You entered: " << integer << endl << endl;

	return 0;
}
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>
#include <limits>       // std::numeric_limits

using namespace std;

int main()
{
	int integer;

	cout << "Enter an integer: ";
	cin >> integer;
	cin.ignore();

	while (!cin)
	{
	    cin.clear();
	    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input		
		
		cout << "You must enter an integer.\nTry again: ";
		cin >> integer;
		cin.ignore();
	}
	cout << "You entered: " << integer << endl << endl;

	return 0;
}
@rafae11: I recommend not doing it that way, see my link above for why.
Last edited on
@LB
@rafae11

Thank you both for your answers, ill read what you linked :)
Topic archived. No new replies allowed.