Dec 8, 2015 at 2:27am UTC
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.
Dec 8, 2015 at 2:32am UTC
That's because your using INT for choice, try using char or string.
Dec 8, 2015 at 2:33am UTC
http://www.cplusplus.com/forum/general/180615/
Dec 8, 2015 at 3:31am UTC
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 Dec 8, 2015 at 3:32am UTC
Dec 8, 2015 at 3:37am UTC
Hello @kemort
what is '\0' for?
thank you.
Dec 8, 2015 at 3:43am UTC
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 Dec 8, 2015 at 3:44am UTC
Dec 8, 2015 at 4:05am UTC
Sorry, what do you mean by 'constant' or do you mean 'const'?
Dec 8, 2015 at 4:44am UTC
'const' means essentially 'read-only' to protect against/avoid the item being accidentally changes. Check out the full details when u have time.