Blog Archive

Friday, December 6, 2013

Formatting Text in C++: Escape Sequences

We now have text games that provide our players with meaningful output, allow our players to make choices, and give our players more than one opportunity to input a correct response. Players might find the text in our text games too overwhelming as it is, because it is a large block of text. Our text game might benefit from a few well-placed blank lines, but we can format text in more sophisticated ways using escape sequences. Escape sequences change the way that output is formatted in cout statements.

Escape sequences begin with a backslash and are followed by another character. The backslash tells the compiler that an escape sequence is being used, and the character that follows the backslash tells the compiler which character to insert into the output. Escape sequences are placed inside of a string literal in a cout statement.

This chart shows several escape sequences that you may want to place in your text game, how they look in code, and how they look in output.

Escape Sequence Chart


Escape Sequence
Name
In Code
In Output
\n
Newline
cout << "1. Fight the evil worm.\n2. 
Teleport away.\n";
1. Fight the evil worm.
2. Teleport away.
\t
Horizontal tab
cout << "What will you do?" << endl;
cout << "1.\tFight the evil worm." 
     << endl;
cout << "2.\tTeleport away."
     << endl;
What will you do?
1.             Fight the evil worm.
2.             Teleport away.
\”
Double quote
cout << "Hello world!" << endl;
cout << "\"Hello,\" said the world." 
     << endl;
Hello world!
“Hello,” said the world.
\\
Backslash
cout << "The save file is in C:\\ 
My Documents." << endl;
 
The save file is in C:\ My Documents.
\a
Alert
cout << "The computer beeped. 
The AI knew about your betrayal.\a" 
     << endl;
 
The computer beeped. The AI knew about your betrayal.
The computer will beep as this text appears on the screen.

Experiment with escape sequences until you find a format that works for your text game.

No comments:

Post a Comment