C++从文件中读取不同类型的数据,直到有一个以数字开头的字符串

C++ read different kind of datas from file until there's a string beginning with a number

本文关键字:一个以 字符串 开头 数字 数据 文件 读取 同类型 C++      更新时间:2023-10-16

在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并不完全准确 - 如果需要,您仍然可以只获取一行的一部分。

相关文章: