c++ - 我如何读取文件的最后一行

标签 c++ file ifstream

我在阅读文件程序后尝试了这个,程序被关闭了。它没有显示文件的最后一行,完成读取后应该在 new1 字符串指针中。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
std::string line;
int i;
std::string *new1;
new1 = new string;
ifstream myfile ("path.txt");
   while (myfile)
   {
         getline (myfile,line);
         cout << line<<endl;
         new1=line;

   }              
   cout<<new1<<endl;
   myfile.close();
      cin.get();
      return 0;
}

提前致谢。

最佳答案

代码的主要变化:

替换

while (myfile)
{
     getline (myfile,line);
     cout << line<<endl;
     new1=line;

}

通过

while (getline (myfile,line))
{
   cout << line<<endl;
   new1=line;
}              

第一个不起作用的原因是在您读完最后一行后,while (myfile) 继续评估为 while(true)。那时,getline(myfile, line) 没有成功。您没有捕获该返回值并正确处理它。

其他改进:

替换

std::string *new1;
new1 = new string;

std::string new1;

不确定为什么您认为需要 new1 作为指针。如果您继续将 new1 保留为指针,则必须将 while 循环更改为:

while (getline (myfile,line))
{
   cout << line<<endl;
   *new1=line;  // *new1, not new1.
}

当然你也必须添加一行来删除new1

关于c++ - 我如何读取文件的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27009847/

相关文章:

c++ - 使用 LLVM 检测 C/C++ 代码

powershell - 如何使用PowerShell按日期对文件进行分组?

c++ - 为什么 ifstream 两次返回输入文件的最后一个值?

C 编程 我试图从 2 个 txt 文件切换内容

Java - 尝试写入文件 2 次或更多次时出现 BufferOverflowException

c++ - ifstream 无法在递归调用中打开

c++ - 到底什么时候检查 std::ifstream::good() ?

c++ - 如何在 Visual C++ 2013 中将函数对象作为参数传递?

c++ - 如何计算 vector 中相等的相邻元素?

c++ - 当一切正确时,代码继续打印 "1"