如何在逐行读取文件时跳过字符串

How to skip a string when reading a file line by line

本文关键字:字符串 文件 读取 逐行      更新时间:2023-10-16

当从具有名称和值对的文件中读取值时,我设法跳过了名称部分。但是,有没有其他方法可以跳过名称部分,而不声明一个伪字符串来存储跳过的数据?

示例文本文件:https://i.stack.imgur.com/94l1w.png

void loadConfigFile()
{
    ifstream file(folder + "config.txt");
    while (!file.eof())
    {
        file >> skip;
        file >> screenMode;
        if (screenMode == "on")
            notFullScreen = 0;
        else if (screenMode == "off")
            notFullScreen = 1;
        file >> skip;
        file >> playerXPosMS;
        file >> skip;
        file >> playerYPosMS;
        file >> skip;
        file >> playerGForce;
    }
    file.close();
}

您可以使用std::cin.ignore忽略输入,最多可以忽略指定的分隔符(例如,新行,跳过整行)。

static const int max_line = 65536;
std::cin.ignore(max_line, 'n');

虽然许多人建议指定最大值std::numeric_limits<std::streamsize>::max(),但我不建议。如果用户不小心将程序指向了错误的文件,他们不应该等到程序消耗了过多的数据后才被告知有问题。

另外两点。

  1. 不要使用while (!file.eof())。这主要会导致问题。对于这样的情况,您真的想定义一个structclass来保存相关值,为该类定义operator>>,然后使用while (file>>player_object) ...
  2. 你现在的阅读方式实际上是一次读一个"单词",而不是整行。如果你想读一整行,你可能想用std::getline