Loop question

Hello again,

I was just wondering what the best way to create a loop for an input of a number 1-50 would be. I do not want to allow anything under or over that mark. I tried an if/else loop but it would only check it one time and on the second attempt if I put in a number outside of 1-50 it would accept it. Any tips? Thanks everyone.
1
2
3
4
5
6
7
	int UserNum=0;
	do
	{
		printf("Please enter a number 1-50: ");
		scanf(" %d", &UserNum);
	}
	while (UserNum != 1-50);
You cant use statements like that. It would have to be while (UserNum < 1 || UserNum > 50)

Another way would be like this or something along the lines. You could also simplify the while statement if you want.

1
2
3
4
5
while( std::cout << "Please enter a number 1- 50: " << std::flush
           && !std::cin >> UserNum && ( UserNum < 1  || UserNum > 50 ) )
{
    std::cout << "Invalid Selection" << std::endl;
}
A do-while loop is a good choice because you want the loop to execute at least once. But you can't use a range of numbers for the condition of the loop.

With what you have, add a Boolean flag before the do statement and set it to true. Then add a check of UserNum after your scanf. Set the flag to false if the number is in range. Your while statement would look like this if you named your flag bNotValid:

1
2
3
4

while( bNotValid );

Thank you, giblit. I should have realized that but thanks for your insight.

Edit: Thank you as well, kooth. I have yet to work with flags but I am actually going to be reviewing that this Monday, coincidentally enough. Thanks!
Last edited on
not entirely true. You can use && and || operators to check multiple bools. Also the < > = == operators return booleans. So you can do while( number > 1 )
Topic archived. No new replies allowed.