Game Development Reference
In-Depth Information
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
The entry point for our program when using GCC is:
int main()
Listing 1-1 showed that the entry point when using MSVC was:
int _tmain(int argc, _TCHAR* argv[])
The first four lines of the main function are used to obtain a random number. The srand function
carries out an operation known as seeding. This uses the current time returned from the time
function to generate a sequence of random numbers.
// Generate unique random numbers using the current time
srand(time(NULL));
We declare and define a variable, numberToGuess , to store the value that we would like our player to
guess. The rand function returns the number and we use the modulus operator ( % ) to ensure that the
number remains less than 100. We cover the modulus operator in more detail in Chapter 3.
// Get a random number between 0 and 99
unsigned int numberToGuess = rand() % 100;
The remaining code is similar to Listing 1-1. We use cout to write text for the player to read and use
cin to allow the player to enter a guessed number. We finish by returning 0.
cout << "Guess a number between 0 and 99" << endl;
unsigned int playersNumber {};
cin >> playersNumber;
cout << "You guessed: "
<< playersNumber
<< " The actual number was: "
<< numberToGuess
<< endl;
return 0;
 
Search WWH ::




Custom Search