Summary
In this lesson, you learned that:
- A value of type
std::stringis called a string.+=adds a string or a singlecharto its end,std::string(5, '#')creates a string of five#, andempty()tells you whether a string has no characters. text.substr(start, length)returns a new string:lengthcharacters from the indexstart. Without the length, the part goes to the end. A length past the end takes the characters there are, but a start past the end stops the program withstd::out_of_range.text.find(part)returns the index where a string or a character first occurs, andtext.find(part, from)starts searching at the indexfrom. When it finds nothing, it returnsstd::string::npos. Compare the result withstd::string::npos; on its own, it isn't a yes or a no.- With
find()andsubstr(), you split a string, for example a command at the space: the part before it issubstr(0, space), the part after itsubstr(space + 1). Check first that the space is there. <and>compare strings in alphabetical order, by the codes of their characters. Uppercase letters come before lowercase ones, and a string comes before a longer one that starts with it.for (const std::string& item : inventory)reads the strings in a vector without copying them, andfor (char& c : text)changes the characters of a string.<cctype>works with single characters.std::toupper()andstd::tolower()return a changed character; store it in achar, because printed straight away, it's a number.std::isupper(),std::isalpha()andstd::isdigit()answer a question, so you use them as conditions.insert(),erase()andreplace()change the string itself. Together withfind(), they replace words, as in a chat filter.std::stoi()andstd::stod()turn a string into anintor adouble, andstd::to_string()turns a number into a string. A string that doesn't start with a number stops the program, so check it before you convert it.- Strings that you measure, cut, search or compare should have no letters with accents, because such a letter takes two
chars.
In the next lesson, Structs, you will create a type of your own, which keeps a monster's name, health and attack together in one variable.
Instructions
- 1
Let's practice with a text adventure once more. Above
main, write a functionhealthBarwith the parametershealthandmaxHealth, which returns the health bar as a string, as in the first exercise of this lesson. Inmain, printBefore:and the bar:Before: [####------]. The test also runs your program with other values. - 2
Below that, carry out the command: split it at the space into the verb and the number. When the verb is
heal, add the number tohealth, but never abovemaxHealth. Any other verb only printsUnknown command:and the verb. Then printAfter:and the bar again:After: [#######---]. The test also runs your program with other commands.