convert if to switch
Apr 24, 2019 at 4:41pm UTC
I have a long treasure hunt program which compiles ok but for the sake of better coding I was wondering how to convert these if statements to a switch if I can. any help would be appreciated
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
//write loop to find the treasure
for (count = 20; count > 0; --count)
{
cout << " Please enter the direction which you want to move: \n" ;
cin >> direction;
cout << " You have " << count << " turns remaining\n" ;
if (direction == 'n' )
cout << y++ << endl << name << " moved North\n" ;
else if (direction == 's' )
cout << y-- << endl << name << " moved South\n" ;
else if (direction == 'e' )
cout << x++ << endl << name << " moved East\n" ;
else if (direction == 'w' )
cout << x-- << endl << name << " moved South\n" ;
Apr 24, 2019 at 4:48pm UTC
Like
1 2 3 4 5
switch ( direction ) {
case 'n' :
cout << y++ << endl << name << " moved North\n" ;
break ;
}
Apr 24, 2019 at 5:57pm UTC
Yes that works thanks salem c
Topic archived. No new replies allowed.