C++ stringstream value extraction

IDDQD picture IDDQD · Jun 18, 2015 · Viewed 10k times · Source

I am trying to extract values from myString1 using std::stringstream like shown below:

// Example program
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
  string myString1 = "+50years";
  string myString2 = "+50years-4months+3weeks+5minutes";

  stringstream ss (myString1);

  char mathOperator;
  int value;
  string timeUnit;

  ss >> mathOperator >> value >> timeUnit;

  cout << "mathOperator: " << mathOperator << endl;
  cout << "value: " << value << endl;
  cout << "timeUnit: " << timeUnit << endl;
}

Output:

mathOperator: +
value: 50
timeUnit: years

In the output you can see me successfully extract the values I need, the math operator, the value and the time unit.

Is there a way to do the same with myString2? Perhaps in a loop? I can extract the math operator, the value, but the time unit simply extracts everything else, and I cannot think of a way to get around that. Much appreciated.

Answer

Christophe picture Christophe · Jun 18, 2015

The problem is that timeUnit is a string, so >> will extract anything until the first space, which you haven't in your string.

Alternatives:

  • you could extract parts using getline(), which extracts strings until it finds a separator. Unfortunately, you don't have one potential separator, but 2 (+ and -).
  • you could opt for using regex directly on the string
  • you could finally split the strings using find_first_of() and substr().

As an illustration, here the example with regex:

  regex rg("([\\+-][0-9]+[A-Za-z]+)", regex::extended);
  smatch sm;
  while (regex_search(myString2, sm, rg)) {
      cout <<"Found:"<<sm[0]<<endl;
      myString2 = sm.suffix().str(); 
      //... process sstring sm[0]
  }

Here a live demo applying your code to extract ALL the elements.