how to ask for input again if input validation failed

I'm writing a simple program where the user enters the month (1-12) and the program displays how many days are in the month. How do I make it so if it's not a valid input, it asks the user for the month again?

I tried having a return main(); and it works, and I have no idea why. However, it continues running forever if I enter a letter.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 #include <iostream>

using namespace std;

int main()
{
	double month;
	cout << "Enter the month (1-12): ";
	cin >> month;
	cout << endl << endl;
	if (cin.fail() || month >= 13)
	{
		cout << "Error: That is not a valid month." << endl << endl;
		return main();
	}
	else if (month == 1)
	{
		cout << "31" << endl;
	}
	else if (month == 2)
	{
		cout << "27 or 28" << endl;
	}
	else if (month == 3)
	{
		cout << "31" << endl;
	}
	else if (month == 4)
	{
		cout << "30" << endl;
	}
	else if (month == 5)
	{
		cout << "31" << endl;
	}
	else if (month == 6)
	{
		cout << "30" << endl;
	}
	else if (month == 7)
	{
		cout << "31" << endl;
	}
	else if (month == 8)
	{
		cout << "31" << endl;
	}
	else if (month == 9)
	{
		cout << "30" << endl;
	}
	else if (month == 10)
	{
		cout << "31" << endl;
	}
	else if (month = 11)
	{
		cout << "30" << endl;
	}
	else if (month = 12)
	{
		cout << "31" << endl;
	}
	cout << endl;
	system("PAUSE");
	return 0;
}
I tried having a return main();
Never call main() manually. It is not supposed to be called manually.

How do I make it so if it's not a valid input, it asks the user for the month again?
Use loop to validate input:
1
2
3
4
5
6
7
int month; //Do not use floating point unless really needed
while(!(std::cin >> month) || month > 12 || month < 1)
{
    std::cin.clear(); //Clear error flags to allow normal input
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore errorneous output still sitting in buffer
    std::cout << "Error: That is not a valid month. Enter again\n";
}


http://stackoverflow.com/questions/19521320/why-do-i-get-an-infinite-loop-if-i-enter-a-letter-rather-than-a-number
Why you use double for mounth, it's betret int (integer), because mounth can't be 6.6. For 11 and 12 you use only (=), need (==). Do you know do{}while loop?
Topic archived. No new replies allowed.