Ask the user to enter a number between 5 and 8 (inclusive).
Use a while loop to validate the choice. It should continue until the user puts the correct number
I am stuck here
My soln so far-
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <cstdio>
usingnamespace std;
int main(){
int input;
cout<<"Enter a number between 4 and 9:\n";
cin>>input;
while (5>input||input>8)
cout<<"Invalid number, please try again:\n";
}
This throws me into an infinite loop. I can't seem to understand the problem. Help!
You just failed to add the "{" at start of the while.
So, your code should be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <cstdio>
usingnamespace std;
int main()
{
int input;
cout<<"Enter a number between 4 and 9:\n";
cin>>input;
while (5>input||input>8)
{
cout<<"Invalid number, please try again:\n";
}
}
EDIT: Sorry. My fault. Didn't see that the "}" was from main, not from while.
Well yes. It's kinda' infinite loop. You just ask for ONE number. The "while" statement runs for the number you entered. But after that, it won't stop unless you use a "break;" or a "goto"
#include <iostream>
#include <cstdio>
usingnamespace std;
int main()
{
int input;
char ok;
cout<<"Enter a number between 4 and 9:\n";
cin>>input;
while (5>input||input>8)
{
cout<<"Invalid number, please try again:\n";
cout << "Try with other number ("y" = yes / "n" = no) ?\n";
cin >> ok;
if (ok == 'y');
cin >> input;
else
{
if (ok == 'n')
cout << "You have chosen to exit.";
break;
}
}
return 0;
}
What if I didn't want it to be an option to select another number, just wanted the program to automatically prompt the use for another number. is that possible? ._.