字符串有' '太多了
String has a ' ' too much
我创建了一个名为FileReader的类。这是我这门课的读函数。它打开一个文件并读取它。当然,它将文件的内容放在类的一个名为"content"的变量中。在最后一行。
std::string file_content;
std::string temp;
std::ifstream file;
file.open(filepath,std::ios_base::in);
while(!file.eof()){
temp.clear();
getline(file, temp);
file_content += temp;
file_content += 'n';
}
file_content = file_content.substr(0, file_content.length()-1); //Removes the last new line
file.close();
content = file_content;
我正在打开的文件有以下内容:
"你好 nWhat nCool"。
当然,我没有在我的文本文件中确切地写n。但是,正如您所看到的,末尾没有新行。
我的问题是,"内容"有,每当我打印到屏幕上,一个新的行结束。但是我去掉了最后一行…怎么了?
经典错误,在阅读之前而不是之后使用eof
。这是正确的
while (getline(file, temp))
{
file_content += temp;
file_content += 'n';
}
或者如果您必须使用eof
,请记住在 getline
之后使用,而不是在
for (;;)
{
getline(file, temp);
if (file.eof()) // eof after getline
break;
file_content += temp;
file_content += 'n';
}
令人难以置信的是,有多少人认为eof
可以预测下一次读取是否会有eof问题。但它没有,它告诉你最后一次读取有eof问题。在C和c++的整个历史中都是这样的,但这显然是违反直觉的,因为很多很多人都犯了这个错误。
eof
直到您尝试读取超过文件末尾时才会被设置。你的循环对三行代码进行了四次迭代;但是,最后一次迭代不读取任何数据。
更正确的方法是将while循环更改为while (std::getline(file, temp))
;这将在第三次读取后到达文件末尾时终止循环。
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 错误:字符数组的初始值设定项太多
- 对象实例化调用构造函数的次数太多
- Levenshtein 两个文件的距离花费了太多时间
- 我有三个 getline,但是一旦编译,输入就太多了
- 将使用太多的纹理插值器 - 带旋转的着色器
- C/C++:socket() 创建在循环中失败,打开的文件太多
- 使用Visual Studio在虚幻引擎中创建一个新的类c ++给了我太多的错误
- C++:数组<>初始值设定项太多
- GLib-ERROR:为GWakeup创建管道:打开的文件太多
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 我会导致太多内存泄漏,以至于我的计算机无响应吗?
- ZeroMq:打开的文件太多.在同一对象上连续增长的fd使用数
- exe 上的字符串命令透露了太多
- 将字符串与数字进行比较,而无需编写太多运算符重载函数
- 整数/浮点数/字符串值之间的操作,组合太多
- 标准::字符串数组的初始值设定项太多
- 函数调用的参数太多,预期为 0,有 1。 "InfInt.h"字符串函数
- 当我输入字符串时,我的菜单重复了太多次
- 字符串有' '太多了