typestar

String streams in C++

Build strings with << and parse them back with >>, no manual conversion in sight.

#include <sstream>
#include <string>

std::string tag(const std::string &name, int count) {
    std::ostringstream out;
    out << name << " x" << count;
    return out.str();
}

int sum_line(const std::string &line) {
    std::istringstream in(line);
    int total = 0;
    for (int value; in >> value;) {
        total += value;
    }
    return total;
}

How it works

  1. std::ostringstream collects anything << accepts; str() hands back the finished string.
  2. std::istringstream turns a string into an input stream, so >> extracts typed values.
  3. The loop reads ints until the stream runs dry — in >> value turns false at the end.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
316
Tokens
99
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 2 of 3 in Strings & streams, step 20 of 27 in Language basics.

← Previous Next →