How can I continue my question until the user enter the valid input?

Hello, I am writing a code in c++ and I need to ask the user to enter the number between 0-4

0= quit
1-4=do something

so at first I use do and while
for example
do
{
}
while (choice!=0);

so it goes back if the user enter any integer but0-4. However when the user enter a character. it won't work and it will quit right away.

Please help. if you wanna see my code please comment below.

That's because your using INT for choice, try using char or string.
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/general/180615/
Hello, @SamuelAdams (841)

but my code is like this and it says switch quantity is not an integer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main(){

     
       do
    {  string choice;
        choice = selected_option();
    switch(choice)
case0:
{ //this is quit}
case1:
{// do something}
case2:
{...}
case3:
{}
case4:
{}
}
while ( choice!=0);
}
return 0;

}
closed account (48T7M4Gy)
Maybe this is something you could build on:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main()
{
	int number = 0;
	char choice = '\0';

	while (cin >> choice)
	{
		number = choice - '0';
		cout << number << endl;
	}
      
       return 0;
}
Last edited on
Hello @kemort
what is '\0' for?

thank you.
closed account (48T7M4Gy)
I like the idea (habit) which is conventional good practice of initialising all variables with a value so I made it zero. That way if it never gets changed you don't get rubbish values creeping in.

The other good practice is not to use using namespace std; but I was lazy this time. Old habits die hard.
Last edited on
is it like constant ?
closed account (48T7M4Gy)
Sorry, what do you mean by 'constant' or do you mean 'const'?
yes
closed account (48T7M4Gy)
'const' means essentially 'read-only' to protect against/avoid the item being accidentally changes. Check out the full details when u have time.
Topic archived. No new replies allowed.