我在看完文件后试了一下。它没有显示文件的最后一行,它应该在完成读取后在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;
}
提前谢谢。
发布于 2014-11-19 05:59:40
对代码的主要更改:
替换
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
。
发布于 2014-11-19 06:03:42
这是因为在结束循环之前最后一个值是eof。
用这个:
while (getline (myfile,line))
{
cout << line<<endl;
new1=line;
}
https://stackoverflow.com/questions/27009847
复制相似问题