如何解析istringstream C++



我需要从stream-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,10nAnastacia;Volivach,30nJohn;Brown,60nJames;Bond,30n" );
    a . Add ( is );
    return 0;
}

如何解析这条线

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

name;surname,data

这有点脆弱,但如果你知道你的格式与你发布的格式完全相同,那就没有错:

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

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

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;

相关内容

  • 没有找到相关文章

最新更新