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
std::ostringstreamcollects anything<<accepts;str()hands back the finished string.std::istringstreamturns a string into an input stream, so>>extracts typed values.- The loop reads ints until the stream runs dry —
in >> valueturns false at the end.
Keywords and builtins used here
constforintreturnsum_linetag
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.
Step 2 of 3 in Strings & streams, step 20 of 27 in Language basics.