Search code examples
c++stringistringstream

Trouble understanding istringstream in C++


I am new to C++ and I was wondering how I can understand what functions and classes do. For example I was told to use "istringstream" for a homework assignment. I have looked online and found the site cplusplus.com with a lot of references. The problem I have is understanding the reference page.

On the "istringstream" reference page I am given the following code:

// istringstream constructors.
#include <iostream>     // std::cout
#include <sstream>      // std::istringstream
#include <string>       // std::string

int main () {

  std::string stringvalues = "125 320 512 750 333";
  std::istringstream iss (stringvalues);

  for (int n=0; n<5; n++)
  {
    int val;
    iss >> val;
    std::cout << val*2 << '\n';
  }

  return 0;
}

In the code above, it does exactly what I need it to do for my assignment but I do not understand WHY it works. So they created a istringstream object called iss, then later used "iss >> val". That is the part I am confused with. What exactly does it do?

I have tried reading the text above where it explains what each function in the class does but I did not understand any of it. For example, one of the first lines on the reference page says

default (1)   explicit istringstream (ios_base::openmode which = ios_base::in);

How do I interpret this line? From what I can see it is a function that takes one argument but what is "ios_base::openmode which = ios_base::in".


Solution

  • I believe this is the page you're looking for. This defines that mysterious >> operator. It is overloaded several different ways, which means it's working like a scanf function for several different data types.

    Your compiler looks at iss >> val and says "Hmm...iss is an istringstream and val is an int. Aha! Looks like istringstream has an operator>> that takes an int&, I'll use that!"

    Edit: istream has an operator>> for int&. istringstream inherits those.