So i make a turn based dos game, And i have a switch() function which gives me a bug.. :
int hp;
int mana;
do
{
cout<<"Enter your arg here";
cin>>choice;
cout<<"Hahaha that won't stop me";
switch(choice)
{
case 1:
mana--;
mana--;
hp--;
hp--;
cout<<"Woosh";
}
}
while(1)
{
cout<<endl;
}
Ok so let me explain the bug :
- When the player inputs choice variable it will just skip the switch() function an just go continue with cout<<"Hahaha that won't stop me";. How do i fix that? PS : Sorry for my bad english, and if there is a misswriting on this post. I'm so sorry about that.
CodePudding user response:
First of all, switch is not a function, it's a statement. That means, it doesn't behave like functions. What you've written here doesn't match with what you want. What the program does is:
- printing the first line
- reading the input
- printing the second line
- switching on the input
What you want is:
- printing the first line
- reading the input
- switching on the input
- printing the second line on default case
So let's reorder your code.
cout << "Enter your arg here";
cin >> choice;
switch (choice)
{
case 1:
mana -= 2;
hp -= 2;
cout << "Woosh";
break;
default:
cout << "Hahaha that won't stop me";
break;
}
And don't forget to write break;
on every case, including default one.
CodePudding user response:
First of all, switch is not a function, it is a statement: it is basically a bunch of if ==
statements combined. So, what your switch statement is equivalent to:
if(choice==1)
{
mana-=2;
hp-=2;
cout << "Whoosh!";
}
So, your code is not working, because it will only print "Whoosh!" if you type the number 1.
Also, you should know, that x--
is equivalent to x-=1
which is equivalent to x=x-1
. So, instead of writing mana--;mana--;
, you can write x-=2;
.
It would be very helpful if you could include more of your code, for us to better understand your problem.