Game Development Reference
In-Depth Information
Note There are more functions supplied by C++ for working with C style strings; however, it is better to use
the string class supplied by the Standard Template Library (STL) in modern C++ programs. We cover
STL strings in Chapter 13. You can find a reference for C style string functions at
www.cplusplus.com/reference/cstring/
Text Adventure Game
As you work through this topic we will build a text adventure game on the console. In this chapter
we have looked at arrays, pointers, and C style strings. In the last two chapters we have looked at
types, operators, and interacting with the user using cin and cout .
We will begin by making our game a personal experience by asking the players for their name.
This will be used to make the game seem as though it knows the players while they play through the
game. Listing 4-10 shows the code that asks the players for their name.
Listing 4-10. Asking for the Player's Name
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Welcome to Text Adventure!" << endl << endl;
cout << "What is your name?" << endl << endl;
char playerName[1024];
cin >> playerName;
cout << endl << "Hello " << playerName << endl;
return 0;
}
This code stores the player's name into a char array that contains 1,024 letters. The game would run
into trouble if the player was to enter more characters than this, so we will use a string instead, as
shown in Listing 4-11.
Listing 4-11. Using an STL String for the Player Name
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Welcome to Text Adventure!" << endl << endl;
cout << "What is your name?" << endl << endl;
 
Search WWH ::




Custom Search