Skip to content
Lesson 4 of 15

Step 1 of 5 · Reading · ~3 min

Learn

Strings

std::string

By the end of this lesson you can store text in a std::string, read a whole line of input into one, look at single characters, and hand a string to the <algorithm> functions that rearrange its characters in place.

A string is a value

#include <string>

std::string city = "Oslo";
std::string label = city + " Airport";   // + joins two strings
label += "!";                            // += appends in place
std::cout << label << "\n";              // Oslo Airport!
std::cout << label.size() << "\n";       // 13

A std::string knows its own length (size()), grows when you append, and frees its memory when it goes out of scope. == compares the text itself: city == "Oslo" is true. Copying one string into another copies the characters, so changing the copy leaves the original alone.

Characters and positions

A position (also called an index) is a number counting from 0. s[i] is the char stored at position i, and you can overwrite it.

std::string code = "TRAIN";
//                  01234
std::cout << code[0] << code[4] << "\n";   // TN
code[0] = 'B';
std::cout << code << "\n";                 // BRAIN
std::cout << code.substr(1, 3) << "\n";    // RAI  (start 1, length 3)

code[9] reads past the end with no check: the result is undefined. code.at(9) checks and stops the program with an std::out_of_range error instead.

Reading a line, not a word

std::string title;
std::cin >> title;               // input "Blue Moon"  ->  title is "Blue"
std::getline(std::cin, title);   // input "Blue Moon"  ->  title is "Blue Moon"

>> stops at the first space and silently leaves the rest in the input. std::getline takes everything up to the end of the line, spaces included. When the input is described as a line, use getline.

Ranges: begin() and end()

Functions in <algorithm> do not take a string directly. They take a range: two iterators, x.begin() marking the first character and x.end() marking the spot just past the last one. Most of them work in place and return nothing (void), so you call them as a statement and then print the string.

#include <algorithm>

std::string letters = "banana";
std::sort(letters.begin(), letters.end());   // prints nothing
std::cout << letters << "\n";                // aaabnn

Shrink the range and only part of the string changes. word.begin() + 1 starts one character later:

std::string word = "dcba";
std::sort(word.begin() + 1, word.end());     // position 0 untouched
std::cout << word << "\n";                   // dabc, not abcd

Other functions in <algorithm> use the exact same call shape. std::reverse(first, last) puts the characters of the range in the opposite order, in place, and also returns void.

Common mistakes

  • Reading with >>. On input Blue Moon you only get Blue, so a transformation of it prints eulB and the second word is lost. Any line containing a space exposes this.
  • A range that is one short. Writing x.begin() + 1 or x.end() - 1 leaves the first or last character where it was: dcba sorted that way gives dabc.
  • Using the return value. title = std::sort(...) does not compile (no match for operator= with void). The function changes the string; it gives nothing back.
  • Working word by word. Treating each word separately gives a different answer from treating the whole line as one range of characters.

Your exercise

Read one line and print its characters in reverse order. The starter already reads the line with getline and prints the string; you add the one statement in between that rearranges it. The spaces are characters too, so they move along with everything else.

Up nextOutput FormattingStrings

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…