简体   繁体   中英

fstream object is not reading data from the file?

#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();



}

This shows error but if i make ifstream object to write and ofstream object(which is different than object of ifstream) to read then only it is executed. Thank you for helping me

<fstream> contains ofstream and ifstream classes.

You should use ofstream object to write data to file:

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

and ifstream object to read data from file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM