4

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

示例文本文件:http: //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();
}
4

1 回答 1

6

您可以使用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.
于 2013-07-18T15:29:42.900 回答