gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:42:45 24 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用 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 .

关于c++ - 逐行读取文件时如何跳过字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17727691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com