Learn C++ · lesson 3 of 61 · about 6 minutes
Text and True/False
Name your hero with std::string, and keep yes-or-no facts in bool.
What you'll learn
- Use std::string for text
- Use char for a single character
- Print booleans as true and false
Name your hero
Numbers aren't enough. Your hero needs a name, and your game needs to remember yes-or-no facts, like whether you're carrying a torch. The type of a variable decides what it can hold:
| Type | Holds | Example |
|---|---|---|
| int | whole numbers | 42 |
| double | decimals | 1.5 |
| char | one character | 'B' |
| bool | true or false | true |
| std::string | text | "Ada" |
std::string needs #include <string> at the top.
A hero in five types
#include <iostream>
#include <string>
int main() {
std::string hero = "Ada";
int level = 3;
double speed = 1.5;
char rank = 'B';
bool hasTorch = false;
std::cout << hero << " L" << level << " speed " << speed << " rank " << rank << "\n";
std::cout << std::boolalpha << "Torch: " << hasTorch << "\n";
}Output
Ada L3 speed 1.5 rank B
Torch: falseA type is a promise
A variable keeps its type for good. If you try to put text into an int, C++ doesn't guess what you meant: the program doesn't compile.
That's part of why C++ is fast. The compiler knows exactly what every variable holds before the game ever runs, so it doesn't have to check while it's running.
Tip
By default cout prints bools as 1 and 0. Sending std::boolalpha first makes it print true and false instead.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.