user1779502
user1779502

Reputation: 593

How to do parsing istringstream C++?

I need to print some data from stream - istringstream ( in main () ).

example:

void Add ( istream & is )
{
    string name;
    string surname;
    int data;

    while ( //something )
    {
        // Here I need parse stream

        cout << name;
        cout << surname;
        cout << data;
        cout << endl;
    }

}

int main ( void )
{
    is . clear ();
    is . str ( "John;Malkovich,10\nAnastacia;Volivach,30\nJohn;Brown,60\nJames;Bond,30\n" );
    a . Add ( is );
    return 0;
}

How to do parsing this line

is.str ("John;Malkovich,10\nAnastacia;Volivach,30\nJohn;Brown,60\nJames;Bond,30\n");" 

to name;surname,data?

Upvotes: 0

Views: 1555

Answers (2)

David
David

Reputation: 28178

This is somewhat fragile, but if you know your format is exactly what you posted, there's nothing wrong with it:

while(getline(is, name, ';') && getline(is, surname, ',') && is >> data)
{
    is.ignore();    //  ignore the new line
    /* ... */
}

Upvotes: 1

If you know the delimiters will always be ; and ,, it should be fairly easy:

string record;
getline(is, record); // read one line from is

// find ; for first name
size_t semi = record.find(';');
if (semi == string::npos) {
  // not found - handle error somehow
}
name = record.substr(0, semi);

// find , for last name
size_t comma = record.find(',', semi);
if (comma == string::npos) {
  // not found - handle error somehow
}
surname = record.substr(semi + 1, comma - (semi + 1));

// convert number to int
istringstream convertor(record.substr(comma + 1));
convertor >> data;

Upvotes: 0

Related Questions