我在阅读文件程序后尝试了这个,程序被关闭了。它没有显示文件的最后一行,完成读取后应该在 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/