0

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?

taocp
  • 23,276
  • 10
  • 49
  • 62
user1779502
  • 573
  • 2
  • 8
  • 16

2 Answers2

1

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
    /* ... */
}
David
  • 27,652
  • 18
  • 89
  • 138
0

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;
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455