【发布时间】:2020-03-28 18:56:44
【问题描述】:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream student;
student.open("details.txt");
string name,UID,sem;
for(int i=0;i<5;i++)
{
cout<<"Enter the name , UID , semester\n";
cin>>name>>UID>>sem;
student<<name<<" "<<UID<<" "<<sem<<endl;
}
string xyz;
while(getline(student,xyz))
{
cout<<xyz<<"\n";
}
student.close();
}
这显示错误,但如果我让 ifstream 对象写入和 ofstream 对象(与 ifstream 的对象不同)读取,那么只有它被执行。 谢谢你帮助我
【问题讨论】:
-
This shows error显示什么错误? -
如果你想从文件中读取使用ifstream,如果你想写入文件使用ofstream。使用 fstream 只会让事情变得更复杂。
-
这并没有解决问题,而是养成使用有意义的值初始化对象的习惯,而不是默认构造它们并立即覆盖它们。在这种情况下,这意味着将
fstream student; student.open("details.txt");更改为fstream student("details.txt");。此外,您无需致电student.close();。析构函数会这样做。
标签: c++ file file-handling