Wanted to check the validity of my code. This is a small function to get the users input 1-9 or send him back to the beginning with wrong input. I am trying to place a switch construct within an infinite loop that will be broken by valid input. What am I doing wrong here. (I know there are different ways to achieve this)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int get_user_input()
{
int user_input(0);
for (;;)
{
cout<<"Enter number between 1 and 9 :";
cin>>user_input;
switch(user_input)
{
case 1: if (user_input>=1 && user_input<=9);break;
case 2: if (user_input<=0 || user_input>=10);continue;
}
cout<<"flag!";
break;
}
return user_input;
}
output: "flag!"for both and only 1 iteration through the loop
I don't think you quite know how switch statements work.
If user inputs 2, then it will trigger case 2. In case 2 you check if user_input is less or equal to 0, or bigger than or equal to 10. Which can never be true. 2 is nor less than 0 or bigger than 10.
Thanks Tarik, I understand about case statements now & the inputs. I'll update a corrected version for posterity.
In case 2 you check if user_input is less or equal to 0, or bigger than or equal to 10. Which can never be true.
I am confused here. In case2 (I'll redo the switch statements after this), this OR statement checks to see whether the user input is out of range, i.e. <0 or >9. If either one is true, doesn't this make for a true condition with the ||? || only needs one true to be totally true.
If its true I send it back to the beginning of the code block and user tries again.
Yes. But, when case 2 is triggered. user_input is equal to 2. Which means that checking if its less than 0 OR bigger than 10 is pointless. Since you know it's 2.
You're also using if statements wrong. This is how an if statement looks like -
1 2 3 4
if (something)
{
// do somethings
}
Yours has a semicolon after the condition, which you're not supposed to have.
It seems like you're new to programming, and what helped me learning was a few tutorials on youtube. This site also good some good ones, you can look up if statements and switch statements. But here is 2 playlists with 70+ videos each on all kinds of basic stuff on C++.
Thanks for the referrals. Actually I am not new to c++; these are just weak areas. I am currently taking a great tutorial. My question would have better been "can one use switch statements inside loops". Instead, I expose my faulty code, mistake of mine. My last question to you is can you compare the same operand in logic operators, e.g. x
x || x ; x && x
I wrote this function instead of using switch statements
1 2 3 4 5 6 7 8 9 10 11
int get_user_input()
{
int user_input(0);
for(;;)
{
cout<<"Enter number between 1 and 9 :";
cin>>user_input;
if (user_input<10 && user_input>0) return user_input;
continue;
}
}