C++ console game

Started by
1 comment, last by Lenny1986 8 years, 3 months ago

Hey guys i am learning c++ out of hobby. I`ve started making small console games to get to know the language better. I made this game where i get a starnge behaviuor that i can`t explain nor can i overcome. Seems that my variable 'amount' is geting overriden by the last object of the array 'slots' when i run the 'roll' function after getting the value for amount using cin. I also tried using getline and stringstream stoping getline on '\n' but still the same result :

#?include? <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void roll(int slots[], int size)
{
srand(time(NULL));
for (int i=0;i<size;i++)
{
slots=rand()%9;
}
}
int main()
{
int money=100;
int amount;
int slots[2];
char play='y';
cout<<"\t\t**** Welcome to Lenny Slots ****"<<endl<<endl;
cout<<endl;
cout<<"\t* * *"<<endl;
cout<<"\t\tDo you wanna play?";
cin>>play;
cin.get();
while(play=='y')
{
cout<<"\nYou have "<<money<<" dollars!"<<endl;
cout<<"How much do you wanna bet?"<<endl;
cin>>amount;
cout<<"Rolling..."<<endl;
roll(slots,3);
cout<<"\t"<<slots[0]<<" "<<slots[1]<<" "<<slots[2]<<endl;
if ((slots[0]==slots[1]) && (slots[1]==slots[2]))
{
money+=amount;
cout<<"Congrats!!! ***winner winner chicken dinner***"<<endl;
}
else
{
money-=amount;
cout<<"Sorry, better luck next time"<<endl;
}
cout<<"Your bank roll is "<<money<<endl;
cout<<endl;
cout<<"Play again?(y/n): ";
cin>>play;
cin.get();
}

}

Advertisement
Please use code tags when posting code. you can do this manually with [ code] [ /code] or use the < > button in the editor.

The immediate issue is that you declare 'slots' with size 2 but use slots[0], slots[1], and slots[2]. If you want three then declare:
int slots[3];
.
Additional:

std::endl places a newline character on the stream and also flushes the stream. If you just want a newline then you can use "\n". For example:
cout << "Your bank roll is " << money << "\n\nPlay again?(y/n): ";
.
Why cin.get() after using cin >> thing ?

srand() should be called only once for the lifetime of the thread (unless you intentionally want to reseed, which is not the case here).

Move the srand() call to the beginning of main().
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

Thanks a lot that did it. I`m not sure why cin.get() is there , tried lots of stuff and probably i forgot to delete that line. Thanks again.

This topic is closed to new replies.

Advertisement