【问题标题】:How to skip a string when reading a file line by line逐行读取文件时如何跳过字符串
【发布时间】:2013-07-18 15:26:50
【问题描述】:

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

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

【问题讨论】:

标签: c++ file-io iostream


【解决方案1】:

您可以使用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: One Example 与您的类似——主要读取文本行,并包括跳过一行(尽管它使用std::getline 这样做)。
猜你喜欢
  • 1970-01-01
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多