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

use*_*ser 3 c++ file-io iostream

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

示例文本文件: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();
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*fin 5

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

static const int max_line = 65536;

std::cin.ignore(max_line, '\n');
Run Code Online (Sandbox Code Playgroud)

虽然许多人建议指定最多类似的东西std::numeric_limits<std::streamsize>::max(),但我不这样做.如果用户意外地将程序指向错误的文件,则在被告知出错之前,他们不应该等待消耗过多的数据.

另外两点.

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