0

我需要从流中打印一些数据 - istringstream(在 main () 中)。

例子:

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

4

2 回答 2

1

这有点脆弱,但如果您知道您的格式正是您发布的内容,那么它没有任何问题:

while(getline(is, name, ';') && getline(is, surname, ',') && is >> data)
{
    is.ignore();    //  ignore the new line
    /* ... */
}
于 2013-05-16T18:42:02.297 回答
0

如果您知道分隔符将始终是;and ,,那么它应该相当容易:

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;
于 2013-05-16T18:21:36.057 回答