C/C++ Arena

Step 3 of 7

std::string is easy

std::string takes care of everything that made C strings painful. It behaves like a normal value: you can copy it with =, compare it with ==, and join strings with +.

#include <iostream>
#include <string>

int main() {
    std::string map = "mirage";
    std::string title = "de_" + map;
    title += " (competitive)";
    std::cout << title << "\n";
    std::cout << title.size() << " chars, first '" << title[0] << "'\n";
    std::cout << (map == "mirage") << " " << (map < "nuke") << "\n";
    std::string copy = map;
    copy[0] = 'M';
    std::cout << map << " " << copy << "\n";
}
de_mirage (competitive)
23 chars, first 'd'
1 1
mirage Mirage

What you get

.size() is a member function: a function that belongs to the object and is called with a dot. You'll write your own in the classes module.

One trap

"de_" + map works because one side is a std::string. But "de_" + "dust2" (two plain literals) doesn't compile (invalid operands to binary expression): literals are C-style char arrays, which turn into pointers, and C++ has no + that joins two pointers. Make sure at least one side of the first + is a std::string.

Your turn: read a first name and a last name, then print Hello, First Last! (N letters) where N is the number of letters in both names (not counting the space).

Previous: Reading with cin Next: bool, auto and range-for