Do-While loop question

1
2
3
4
5
6
7
8
9
10
11
12
13
#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?
Last edited on
Hello noblemin,

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.

Something you can do is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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.
}


Andy
Thanks for the response Andy, really appreciate it!
Hello noblemin,

You are welcome.

Whether it is an if statement or a while loop That bit of code comes in handy.

Andy
Topic archived. No new replies allowed.