Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何解析istringstream C++;?_C++_Parsing_Stream_Cout_Istringstream - Fatal编程技术网

C++ 如何解析istringstream C++;?

C++ 如何解析istringstream C++;?,c++,parsing,stream,cout,istringstream,C++,Parsing,Stream,Cout,Istringstream,我需要从stream-istringstream(在main()中)打印一些数据 例如: void Add ( istream & is ) { string name; string surname; int data; while ( //something ) { // Here I need parse stream cout << name; cout << su

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

这有点脆弱,但如果您知道您的格式与您发布的格式完全一致,那么它没有任何问题:

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