So basically, I have this:

bool getDouble ( double & value, const string & prompt);
int main()
{
	char userSelection;
	do
	{
		cin >> userSelection;
		if (userSelection == '1')
		{
			double radius;
			if (getDouble (radius, "Please enter a value: "))
			{
				cout << "good";
			}
			else
			{
				cout << "bad";
			}
		}
	}
	while (userSelection != 'Q');
	cout << "Thank you for using my program." << endl;
	exit (EXIT_SUCCESS);
}

bool getDouble (double & value, const string & prompt)
{
	cout << prompt;
	if (cin >> value)
	{
		return true;
	}
	return false;
}

I stripped the majority of code out, there was a menu and such, but I took it all away so you could see the main issue. My problem is, that, if the user enters '1', and then an invalid value, such as 't', it loops instead of ending and asking for the menu selection again. I thought since I put

if (getDouble (radius, "Please enter a value: "))

it would just output bad, but it outputs bad forever basically. Is there anything, in my basic knowledge that I'm overlooking? I was thinking something in the while statement, but I'm not sure what. Thanks.

Recommended Answers

All 2 Replies

When you give cin a bad input for "value" (e.g., 't' in your example), the stream goes "bad" and you need to issue a cin.clear(); after line 32 to reset it.

See http://www.cplusplus.com/reference/iostream/ios/clear/ (the example is for a file stream, but it's the same idea)

When you give cin a bad input for "value" (e.g., 't' in your example), the stream goes "bad" and you need to issue a cin.clear(); after line 32 to reset it.

See http://www.cplusplus.com/reference/iostream/ios/clear/ (the example is for a file stream, but it's the same idea)

Thank you! As I was spending hours without help attempting to debug the program, the thought of clearing the input came through my head, and I thought nothing of it. Silly me for forgetting what could have saved me a lot of time. Oh well, now I'll forever remember it. Thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.