2013-05-16 29 views
0

我需要从流 - istringstream(在main())中打印一些数据。如何解析istringstream C++?

例如:

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; 
} 

如何做到解析这一行

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

name;surname,data

回答

0

如果你知道定界符总是会;,,它应该是相当容易:

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; 
1

这是有些脆弱,但如果你知道你的格式是正是你贴什么,有什么错了:

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