This topic is 3851 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I learned how to save to a file using fstream (ofstream). Now if I want to read from that file, what do I do?

Share on other sites
If it is a file on the disk at this point then open it with an ifstream object. The 'i' in ifstream stands for input. The 'o' in ofstream stands for output. Similarly you can use an fstream object for both input and output.

Share on other sites
You create an ifstream object and open the file. Then you extract the data from your file just as you would extract data from the console:

#include <fstream>#include <string>int main(){    int strength, intelligence, gold;    std::string name;    std::ifstream ifile;    ifile.open("myfile.ext");    ifile >> name >> strength >> intelligence >> gold;    return 0;}

Share on other sites
So I made this one but I doesn't work: It shows me the last age was always 73.

#include<iostream>#include<fstream>using namespace std;ofstream ofile ("Test.txt");ifstream ifile ("Test.txt");int main(){    int age;    int last_age;        ifile>>last_age;        cout<<"Enter your age: ";    cin>>age;        cout<<"\nYou have entered "         <<age        <<" .The last time you entered "        <<last_age;        ofile<<last_age;        cout<<"\n\n";        system("PAUSE");       return 0;    }

Share on other sites
Shouldn't

ofile << last_age;

be

ofile << age;

?

As it is, you are reading from the file, the rewriting the same value back to the file, not the new value just entered by the user.

[EDIT]

I'm not convinced you can open the same file with an ifstream and an ofstream at the same time like that anyway. You'd be better to open it for input, read the value then close, then open it for output and write the value:

#include<iostream>#include<fstream>using namespace std;int main(){    ifstream ifile("Test.txt");    int last_age;    ifile >> last_age;    ifile.close();        cout << "Enter your age: ";    int age;    cin >> age;        cout << "\nYou have entered " << age << ".\n";    cout << "The last time you entered " << last_age << ".\n\n";        ofstream ofile("Test.txt");    ofile << age;        system("PAUSE");       return 0;}

Note that:

a) I've moved your variable declarations to just before they are used. C requires all variables in a scope declared at the top. C++ does not.

b) I've not manually closed the ofstream, since that will be done automatically. I have, however, manually closed the ifstream since otherwise the file would still be open when I attempt to open it with the ofstream.

c) I (and you) have omitted to test the streams with ofile.fail() etc after opening to ensure they are open.

• 10
• 10
• 10
• 10
• 12