首页 > 解决方案 > fstream 对象没有从文件中读取数据?

问题描述

#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 的对象不同)读取,那么只有它被执行。感谢你们对我的帮助

标签: c++filefile-handling

解决方案


<fstream>包含ofstreamifstream类。

您应该使用ofstreamobject 将数据写入文件:

ofstream fileOut("file-name.txt");
fileOut << "data";
fileOut.close();

ifstream对象从文件中读取数据:

string data;
ifstream fileIn("file-name.txt");
fileIn >> data;
fileIn.close();

推荐阅读