Switch and If/else C++

Started by
11 comments, last by Kalner 12 years, 1 month ago
When you have it working, consider breaking the actual game logic into a separate function. The main routine will call this with the current difficulty. It might look something like this:

void gameLogic(int max)
{
// ...
}


int main()
{
srand(time(0));

cout << "Welcome to Guess The Number 3.0" << endl;
cout << "Please choose your difficluty. E = Easy M= Medium H = Hard" << endl;

char dif;
cin >> dif;

switch(dif)
{
case 'e':
case 'E':
gameLogic(10);
break;
case 'm':
case 'M':
gameLogic(25);
break;
case 'd':
case 'D':
gameLogic(50);
break;
default:
cout << "Fine I made it hard for you."
gameLogic(100);
break;
}

// Pause goes here, if necessary
}

Advertisement
As a sidenote, if you decide to create local variables inside a case-statement, you need to enclose this in a local scope. At least GCC complains about this because it has to know the scope of the variable (jump to case label [-fpermissive]. crosses initialization of 'int a').
For instance, this will produce the error:

switch (cin.get())
{
case 'E':
int a = 'E';
std::cout << a << std::endl;
break;

case 'B':
int b = 'B';
std::cout << b << std::endl;
break;
}


Which can be resolved using:

switch (cin.get())
{
case 'E':
{
int a = 'E';
std::cout << a << std::endl;
}
break;

case 'B':
{
int b = 'B';
std::cout << b << std::endl;
}
break;
}
Thanks alot guys, especially nife87 and rip-off, you guys got me to fix it then mkae the whole think smaller. =D my first game is complete

EDIT: forgot to mention you Jebbles =D

This topic is closed to new replies.

Advertisement