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.
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";
}
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?