May 1, 2012 at 3:58pm UTC
How does the compiler choose which function to run first?
If I choose not to Play, I want my main() to run.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include <iostream>
#include <ctime>
using namespace std;
int playGame()
{
int count =0; int random = (rand()%10)+1; int choice;
for (int i=0;i<3;i++)
{
cout << "Guess the number 1-10: " ;
cin >> choice;
if (random==choice)
{
cout << "you guessed it right!" <<endl;
count=i+1; break ;
}
else if (i==2)
{
cout << "you lose!" <<endl;
count--; break ;
}
else
{
cout << "Guess again!" <<endl;
}
}
return count;
}
int wantToPlay(int *win, int *loss)
{
bool perfPlay = true ; char option;
while (perfPlay)
{
cout << "Would you play to (P)lay or (Q)uit?" ;
cin >> option;
if (option == 'p' || option == 'P' )
{
int count=playGame();
if (count > 0)
win++;
else
loss++;
}
else
{perfPlay =false ;}
}
return 0;
}
int main()
{
int a;
int b;
wantToPlay(&a,&b);
cout << "You have won " <<a << " games and lost " <<b <<" games" <<endl;
return 0;
system("pause" );
}
Last edited on May 1, 2012 at 10:05pm UTC
May 1, 2012 at 4:06pm UTC
If I choose Q to quit, the game exits.
cout << "You have won " <<a << " games and lost " <<b <<" games"<<endl;
does not occur
Last edited on May 1, 2012 at 4:07pm UTC
May 1, 2012 at 4:29pm UTC
It does, but the program exits immediately after, the dialog may close before you can read it (depending how you are running the program). Also, you need to initialize 'a' and 'b' to 0 in main. Also, you should rename them something meaningful (wins, losses perhaps).
May 1, 2012 at 9:58pm UTC
What makes the program choose to do wantToPlay() before doing main()? Because main called wantToPlay?
May 1, 2012 at 10:07pm UTC
I added system("pause"); but the cmd prompt still exits. Also, in Visual Studio, to keep the cmd line running, is it
Project > Properties > Config Properties > Linker > System > Subsystem > Console?
May 1, 2012 at 10:27pm UTC
main is always executed, it is the entry-point of ALL C++ programs.
May 2, 2012 at 2:39am UTC
tripline, the 2 solutions I use are to either
1) run the program with ctrl+f5 instead of f5
2) end the program with something like "cin >> randomVariable;"
You could also add something like "Sleep(5000)" (Windows.h) if you wanted.