字符串有' '太多了

String has a ' ' too much

本文关键字:太多 字符串      更新时间:2023-10-16

我创建了一个名为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));这将在第三次读取后到达文件末尾时终止循环。