C/C++ Arena

Step 3 of 6

Building strings with ostringstream

std::ostringstream is the output twin: write to it with << like std::cout, then take the result with .str(). It's how you build formatted text without printf-style buffers:

std::string money(long cents) {
    std::ostringstream out;
    out << "
quot; << cents / 100 << "." << std::setw(2) << std::setfill('0') << cents % 100; return out.str(); }

(C++20 also has std::format, covered later. Streams are still everywhere in existing code.)

Your turn: write std::string join(const std::vector<int>& v, const std::string& sep) that returns the numbers separated by sep, like "1, 2, 3".

Previous: Formatting tables with iomanip Next: Reading files with ifstream