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

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();
}

ignore - BoBTFish
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

你能展示你前两个其他点吗?我不知道该如何设计 while (file>>player_object)。先行致谢。 - user
@user: 这个例子与你的类似--主要是读取文本行,并包括跳过一行(尽管它使用std::getline来实现)。 - Jerry Coffin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接