Skip to main content

Processing strings in C++ with

By January 8, 2020No Comments
<sstream> let us store streamed data instead of just outputting it to cout. So we can read whole files.

Input Stream with istringstream object:

“Once an istringstream object has been created, parts of the string can be streamed and stored using the “extraction operator”: >>. The extraction operator will read until whitespace is reached or until the stream fail”

Streaming int

The istringstream can stream AND store int data types in a variable. For example:
int main () 
    string a =("303433 2 3");
    istringstream my_stream(a);
    int n;
    my_stream >> n;
    cout << n << "\n";


  1. Include header file <stream> needed to use the istringstream object
  2. Declare function main whose return value is int
  3. Declare variable a whose value is comprised of the string values of “303433 2 3”
  4. Pass the variable a as an argument to the instringstream object referenced by my_stream variable
  5. Declare variable n which is of the int data type
  6. Once the instringstream object has been created use the extraction operator”: >> to extract parts of the stream into int n
  7. print the contents of “n” with cout << n << “\n” ;

Example 2:

#include <iostream>
using std::cout;
using std::endl;

#include <string>
using std::string;

#include <sstream>
using std::istringstream;

int main()
   string input( "Input test 123 4.7 A" );
   istringstream inputString( input );

   string string1;
   string string2;

   int integer;
   double double1;
   char character;

   inputString >> string1 >> string2 >> integer >> double1 >> character;

   cout << "\nstring1: " << string1
      << "\nstring2: " << string2 << "\n   int: " << integer
      << "\ndouble: " << double1 << "\n  char: " << character;

   return 0;
Example is from here

Leave a Reply