Building a String
In this lesson, you will learn to do more with text: build it from pieces, take a part of it, search in it, change it and turn it into a number. The examples come from games: player names, a chat, a health bar and the commands of a text adventure.
So far, the course has called a value of type std::string a text. Programmers call it a string, because it's a string of characters, one after another, like beads on a thread. From now on, this course says string too.
You know that += adds a string to the end of another one. It adds a single character too, a char in single quotes:
std::string word = "Hi";
word += '!';
std::cout << word << std::endl;This prints:
Hi!When you need the same character many times, you don't have to add it in a loop. std::string(5, '*') creates the string "*****": first the number of characters, then the character. That's handy for a health bar, where each # is a point of health the hero has, and each - a point that is missing:
#include <iostream>
#include <string>
int main() {
int health = 6;
int maxHealth = 10;
std::string bar = "[";
bar += std::string(health, '#');
bar += std::string(maxHealth - health, '-');
bar += ']';
std::cout << bar << std::endl;
return 0;
}This prints:
[######----]The character goes in single quotes. std::string(3, "#") doesn't compile. The error starts with no matching constructor for initialization of 'std::string', which says that no way of creating a string fits these values, and a note below it says no known conversion from 'const char[2]' to 'char' for 2nd argument: the second value should be a char, but it's a string in double quotes.
A string can also be empty, "", with no characters at all. The method empty() tells you whether it is. It returns true or false, so you can use it as a condition, also with ! (not):
std::string message = "";
if (message.empty()) {
std::cout << "Nothing to send" << std::endl;
}This prints:
Nothing to sendmessage.empty() means the same as message.size() == 0, but it says right away what you are asking.
Instructions
- 1
The program shows a player and their health bar. Add
healthcharacters'#'tobar, then the missing health asmaxHealth - healthcharacters'-', and close the bar with the character']'. The program printsHealth: [#######---]. The test also runs your program with other values ofhealthandmaxHealth. - 2
A player can belong to a clan, whose tag is in the variable
tag. Change the first line of the output: whentagisn't empty, print the tag in square brackets and a space before the name,[DK] Aria. A player without a clan has the empty tag"", and then the program prints only the name. Check it withempty(). The test also runs your program with other tags, the empty one among them.