I am trying to learn cin.fail()

I am trying to do input validation to make sure nothing but integers are entered but I cannot get it to work right. I have watched video tutorials. What is happening is the loop is not working correctly. If something other than an integer is input it goes to a blank screen and doesn't loop back and then I will put a number but it still does not proceed. This is the code

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

int main()
{
	int calories;
	bool bFail;
	do {
		cout << setw(5) << " " << "Enter calories: ";
		cin >> calories;

		bFail = cin.fail();
		cin.clear();
		cin.ignore(numeric_limits<streamsize>::max(), 'n');

	} while (bFail == true); 

    return 0;
}
Did you mean to ignore '\n', rather than 'n'?
Yes. Let me try that.
That made it work. I also need to make it do validation in case 0 is entered for either fat grams or calories for the finished product. Is this possible to do another while loop to match that? Thank you for your help.
Probably bFail = cin.fail() || calories == 0; would work. Or do you mean you need a second loop to receive input for fat grams, after calories?
How about bFail = cin.fail() || calories < 1;?
Hello lkordich,

Here is another approach that I have seen many times and it has the advantage of catching more than just the fail bit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
do
{
	cout << setw(5) << " " << "Enter calories: ";
	cin >> calories;

	while (!cin)
	{
		std::cout << "\n Error message" << std::endl;
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.

		cout << setw(5) << " " << "Enter calories: ";
		cin >> calories;

	}
} while (condition);

This tends to work best when the input is to a variable that is defined as a numeric variable.

Your approach will work, but keep in mind there is more than one state bit that could cause "cin" to fail.

Hope that helps,

Andy
Last edited on
Thank you Andy. I got it solved but am still learning. I did use this way.
Topic archived. No new replies allowed.