Do-While Loop not working

I'm writing a program to output a calendar month. When my program executes it only does the "do" part of the loop and automatically treats the first number I enter as false. I'm pretty new to loops so I don't completely understand how they work.

bool validateDays(int numDays)
{
if (numDays >= 28 && numDays <= 31)
return true;
else
do
{
cout << "Not a valid number of days.\n"
<< "Please enter a number between 28 and 31. \n";
cin >> numDays;
}
while (numDays < 28 && numDays > 31);
return numDays;
}

OUTPUT:

Number of days: 30
Not a valid number of days.
Please enter a number between 28 and 31.
30

OUTPUT:

Number of days: 40
Not a valid number of days.
Please enter a number between 28 and 31.
25

Then it ends. I was just testing my functions. Can't seem to figure this one out.
while (numDays < 28 && numDays > 31);

Try changing this to:

while (numDays < 28 || numDays > 31);

Less than 28 OR greater than 31

EDIT:
Just to clarify, seeing as you're new to loops. If you enter 25, yes, it is lower than 28, but at the same time, it's not greater than 31.

i.e.
while( 25 < 28 && 25 > 31 ) is false
Last edited on
Dang, I can't believe I missed that. After I fixed that it just went into an infinite loop.
I just copied a piece of your code and it works fine!

1
2
3
4
5
6
7
8
9
10
11
int numDays = 0;

	do
	{
		std::cout << "Not a valid number of days.\n"
		<< "Please enter a number between 28 and 31. \n";
		std::cin >> numDays;

	}while (numDays < 28 || numDays > 31);

	std::cout << "Done.\n";


Maybe it has something to do with your return statement?

return numDays; instead of return true;?
Thanks for your help, I switched it to a while loop and its working great now :D
Topic archived. No new replies allowed.