Simple while loop

Basically, everything works until the user types anything that ISNT a number. When if you type 1, it excutes 1. when you type two, it excutes 2. when you type 3-9 or 0, it clears the screen and just shows the menu again. but when you input anything else, the loop goes on infinite and the menu keeps flashing (obviously that's the clear screen happening, but i don't know why cin isn't stopping the loop like normal and letting the user input again.+

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
30
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	int input;

	while (true)
	{
		cout << "Login or new account?" << endl
			<< "1): Login." << endl
			<< "2): New Account." << endl
			<< ">:";
		cin >> input;

		if (input == 1)
		{
			break;
		}
		else if (input == 2)
		{
			break;
		}
		else
			system("cls");
	}
	return 0;
}
I see how they did it.. But why is mine doing what it's doing? I swear the else statement covered anything.. Even if it isn't the same type.
This is because the 'fail' flag is set on the cin stream. When this flag is set, it means that the input operation is just skipped and ignored, until you reset it. Hence, you would need to add in a std::cin.clear() statement to reset the fail bit. Also, a std::cin.ignore() call is normally added so that it doesn't sit there failing over and over again until the buffer is empty.
the else would only do that for ints
What do you mean by the fail flag? I swear to god this never happened (as in, the else statement worked even if it wasn't the same type), but I never touched anything called a fail flag. It wouldn't make sense that it is turned on by default because I never had this problem in the past..
See http://www.cplusplus.com/reference/istream/istream/operator>>/ , the 'Return Types' section. This is enabled by default, and you would have had this problem in the past. Could you give us an example where you didn't have this problem?
the exact same thing.. menus in cmd. that's why i posted here. i was so confused it didn't work like any other time. who knows.
Topic archived. No new replies allowed.