Ok. So its a simple program. What I want it to do is each time I run it have the "friendlyCave" be a randomly chosen number between 1 and 2. Then the "game" comes when the user has to choose between one or two to see if he guessed correctly and got the friendlyCave. However when I run the program choosing 1 always gets you to be eaten and choice 2 always is the choice of the dragon sharing his treasure. Please help.
-T
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
cout << "You are in a a land full of dragons. In front of you, you see ";
cout << "two caves. \nIn one cave, the dragon is friendly and will share his";
cout << " treausure with you. \nThe other dragon is greedy and hungry, and ";
cout << " will eat you on sight." << endl;
int cave;
cout << "\nWhich cave do you choose 1 or 2?\n";
cin >> cave;
int friendlyCave = rand() % 2 + 1;
if (cave == friendlyCave)
{
cout << "The dragon pops his head out and shares his treasure.";
}
else
cout << "The dragon pops his head out and eats you in one bite!";
int exit;
cin >> exit;
return 0;
}
Worked beautifully. Cheers man. So did that just seed a number starting at null? I recognize "srand" but when I used it before it was srand(time(0)) under the library <ctime>.
Well, NULL is a C++ macro that is defined as 0. So essentially... they are the same.
Also, the ctime library is completely equivalent to the time.h library as far as I know. I believe there could possibly be a little difference because time.h was used in C and ctime was made to transfer to C++ I believe.
I've never varified that, but that's what I think. Haha. HOWEVER, I do know that time.h and ctime are completely equivalent as far as we are concerned here. Haha.
srand(time(0)) under the library <ctime>
EQUALS
srand (time(NULL));
// You'll need to include the time.h library
Well, NULL is a C++ macro that is defined as 0. So essentially... they are the same.
It's not a standard macro. I think it's actually a WinAPI macro. And I also think it might be slightly different depending on who's defining it. Sometimes it's 0, sometimes it's (void*)0, etc.
Though in C++11, they actually did introduce a standard keyword for this... nullptr. So I recommend using that instead of NULL.
because time.h was used in C and ctime was made to transfer to C++ I believe.
Mostly right. The <ctime> header also puts things in the std namespace, and may have overloaded versions of some of the functions (which are legal in C++... but in C function overloading is not allowed). In C++ it's generally better to use the <cxxx> headers instead of the <xxx.h> headers.