C++ 如何解析istringstream C++;?
我需要从stream-istringstream(在main()中)打印一些数据 例如: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
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
/* ... */
}