WeCodeAcademy

C++ String Streams and Formatting

ExampleC++
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
  ostringstream out;
  out << "Total: " << 42 << ", ratio " << fixed << setprecision(2) << 3.14159;
  cout << out.str() << endl;

  istringstream in("10 20 30");
  int a, b, c;
  in >> a >> b >> c;
  cout << a + b + c << endl;

  cout << setw(8) << "right" << "|" << left << setw(8) << "left" << "|" << endl;
  cout << setfill('0') << setw(5) << 42 << endl;
  cout << hex << 255 << " " << dec << 255 << endl;

  string csv = "a,b,c";
  stringstream ss(csv);
  string part;
  while (getline(ss, part, ',')) cout << "[" << part << "]";
  cout << endl;
  return 0;
}
Output
Total: 42, ratio 3.14
60
   right|left    |
42000
ff 255
[a][b][c]
Quick check

Which class builds a string with << like cout does?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.