在C ++中,我想从包含不同类型数据的输入文件中读取:首先是参赛者的名字(2个或更多带有空格的字符串),然后是ID(没有空格的字符串,总是以数字开头),然后是另一个没有ws和数字的字符串(体育及其实现的地方)。
例如:
Josh Michael Allen 1063Szinyei running 3 swimming 1 jumping 1
我告诉你代码我开始写的然后卡住了..
void ContestEnor::next()
{
string line;
getline(_f , line);
if( !(_end = _f.fail()) ){
istringstream is(line);
is >> _cur.contestant >> _cur.id; // here I don't know how to go on
_cur.counter = 0;
//...
}
}
提前谢谢你的帮助。
你应该考虑使用带有分隔符的std::getline
。这样,您可以分隔空格字符并读取,直到找到数字中第一个字符的字符串。这是一个简短的代码示例(这看起来像家庭作业一样,所以我不想为你写太多的东西;):
std::string temp, id;
while (std::getline(_f, temp, ' ')) {
if (temp[0] >= 0 && temp[0] <= '9') {
id = temp;
}
// you would need to add more code for the rest of the data on that line
}
/* close the file, etc. */
这段代码应该是不言自明的。最重要的是要知道你可以使用std::getline
获取数据直到分隔符。消耗分隔符,就像在换行符上分隔的默认行为一样。因此,名称getline
并不完全准确 - 如果需要,您仍然只能获得一条线的一部分。