如何在逐行读取文件时跳过字符串
How to skip a string when reading a file line by line
当从具有名称和值对的文件中读取值时,我设法跳过了名称部分。但是,有没有其他方法可以跳过名称部分,而不声明一个伪字符串来存储跳过的数据?
示例文本文件:https://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()
,但我不建议。如果用户不小心将程序指向了错误的文件,他们不应该等到程序消耗了过多的数据后才被告知有问题。
另外两点。
- 不要使用
while (!file.eof())
。这主要会导致问题。对于这样的情况,您真的想定义一个struct
或class
来保存相关值,为该类定义operator>>
,然后使用while (file>>player_object) ...
- 你现在的阅读方式实际上是一次读一个"单词",而不是整行。如果你想读一整行,你可能想用
std::getline
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何打开并写入一个名称取自C++中字符串的文件
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将字符串与文件上的数据进行比较
- 用户输入字符串的文件附加问题..C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 使用文件内容作为硬编码字符串
- 将文件复制到自定义位置,存在字符串转换问题
- 将二进制字符串/文件内容从 c++ 传递到节点 js
- 在字符串.h文件中调用函数而不带对象
- 将带有引号和逗号的字符串文件读入字符串数组
- 如何从字符串/文件中分离字符和整数
- 将字符串文件存储到动态数组中
- 如何用C++将字符串文件Txt解析成数组
- 如何用Boost::Spirit解析复杂的字符串文件
- 如何从C语言的第二行读取字符串文件
- 一个很好的性能替代PHP-字符串/文件操作