#include <iostream>
int month;
int main()
{
//month input
do
{
std::cout << "Please enter the month of your birthday as an integer";
std::cin >> month;
} while ((month < 1) || (month > 12));
}
Hello all,
My question is this, why is it when i input a character or phrase into this loop it runs infinitely?
First off try to avoid global variables. for such a short program "month" should be defined in "main".
The problem is with the formatted input std::cin >> month;. This is expecting a number to be entered, so when you enter something that is not a number "cin" will fail an become unusable. After that "month" will either be set to (0) zero or contain a number greater than 12. This may depend on what C++ standard you are using to compile with.
Since the "cin" has failed it will not stop and wait for input, so you end up with an endless loop.
#include <iostream>
#include <limits>
int main()
{
int month;
//month input
do
{
std::cout << "Please enter the month of your birthday as an integer: "; // <--- Changed.
std::cin >> month;
if (!std::cin)
{
std::cout << "\n Invalid input! try again.\n\n";
std::cin.clear(); // <--- Resets the state bits on the stream.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>. Clears the input buffer.
}
} while ((month < 1) || (month > 12));
return 0; // <--- Not required, but makes a good break point.
}