previous | start | next

## String Streams

- The `istringstream` class (`#include<sstream>`) reads characters from a string, and the `ostringstream` class writes characters to a string.
- Using an `istringstream`, you can read numbers that are stored in a `string` by using the `>>` operator.

  >     string input = "January 23, 1955";
  >     istringstream instr(input);
  >     string month;
  >     int day;
  >     string commma.
  >     int year;
  >     instr >> month >> day >> comma >> year;

- Note that this input statement yields a day and year as integers. Had we taken the string apart with `substr`, we would have obtained only strings.
- Converting strings that contain digits to their integer values is such a common operation that it is useful to write a helper function for that purpose.

  >     int string_to_int(string s)
  >     {
  >        istringstream instr(s);
  >        int n;
  >        instr >> n;
  >        return n;
  >     }

previous | start | next