How to extract mixed format using istringstream

Sunil Kundal picture Sunil Kundal · Feb 16, 2014 · Viewed 26.4k times · Source

Why does my program not output:

10
1.546
,Apple 1

instead of

10
1
<empty space>

here's my program:

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

using namespace std;

int main () {
    string str = "10,1.546,Apple 1";
    istringstream stream (str);
    int a;
    double b;
    string c, dummy;
    stream >> a >> dummy >> b >> dummy >> c;
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    return 0;
}

Basically I am trying to parse the comma-separated strings, any smoother way to do this would help me immense.

Answer

2785528 picture 2785528 · Feb 17, 2014

Allow me to suggest the following.

I don't consider it 'smoother', as cin / cout dialogue is not 'smooth', imho.

But I think this might be closer to what you want.

 int main (int, char**)
 {
    // always initialize your variables 
    // to value you would not expect from input        
    int            a = -99;
    double         b = 0.0;
    std::string    c("");
    char comma1 = 'Z';
    char comma2 = 'z';

    std::string str = "10,1.546,Apple 1";
    std::istringstream ss(str);

    ss >> a >> comma1 >> b >> comma2;

    // the last parameter has the default delimiter in it
    (void)getline(ss, c, '\n');  // to get past this default delimiter, 
                                 // specify a different delimiter

    std::cout << std::endl;
    std::cout << a << "   '" << comma1 <<  "'   " << std::endl;
    std::cout << b << "   '" << comma2 <<  "'   " << std::endl;
    std::cout << c << std::endl;

    return 0;
 }

Results: (and, of course, you need not do anything with the commas.)

10 ','
1.546 ','
Apple 1