๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

C++ String Streams

A string stream is a stream that works on a string instead of the screen or a file. It can read values out of one line or build a line up from pieces.

Three numbers from one line

A stringstream holds one line with three numbers. The >> signs read the numbers in order, and their sum prints.

#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::stringstream stream("4 8 15");
  int first;
  int second;
  int third;
  stream >> first >> second >> third;
  std::cout << "Sum: " << first + second + third << "\n";
  return 0;
}

Splitting a comma line

std::getline reads up to each comma here. Each field prints on its own line, in order.

#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::stringstream stream("red,green,blue");
  std::string field;
  while (std::getline(stream, field, ',')) {
    std::cout << field << "\n";
  }
  return 0;
}

Building a line from pieces

An ostringstream takes pieces with the << signs. The str() call gives the finished line, and it prints.

#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::ostringstream builder;
  builder << "Item: " << "Pen" << ", Count: " << 3;
  std::string line = builder.str();
  std::cout << line << "\n";
  return 0;
}

A word and a number

One stream can hold different kinds of value in a row. The word lands in a string and the number lands in an int.

#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::stringstream stream("Score 90");
  std::string label;
  int score;
  stream >> label >> score;
  std::cout << label << ": " << score << "\n";
  std::cout << "Next level: " << score + 10 << "\n";
  return 0;
}

Example

#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::stringstream stream("Hana 80 90");
  std::string name;
  int first;
  int second;
  stream >> name >> first >> second;
  double average = (first + second) / 2.0;
  std::cout << "Name: " << name << "\n";
  std::cout << "Average: " << average << "\n";
  return 0;
}

Key points

  • The <sstream> header gives a program the string stream types.
  • A std::stringstream reads values from a string with the >> signs.
  • Values come out of a string stream in order, from left to right.
  • std::getline with a separator character splits a stream into fields.
  • A std::ostringstream builds text from pieces sent with the << signs.
  • The str() call gives the string an output string stream has built.

In this example, a stringstream holds a name and two scores in one line. The >> signs read the three values in order. The two scores average to 85, and the name and the average print.

Note

A string stream treats its string like a small input or output source.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which stream builds a string from pieces sent with <<?