Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have been trying both write and read a file, but have been unable to

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
    fstream a_file_that_will_be_working_with("storage.txt");
    if (a_file_that_will_be_working_with.is_open()) {
        cout << "is open";
    }
    else
    {
        cout << "is not open";
    }
    a_file_that_will_be_working_with << "first text" << endl;
    a_file_that_will_be_working_with << "second text" << endl;
    while (a_file_that_will_be_working_with)
    {
        // read stuff from the file into a string and print it
        string strInput;
        a_file_that_will_be_working_with >> strInput;
        cout << strInput << '\n';
    }
     return 0;
}

What have I done wrong?
When I use ifstream to read from a file it works, but it doesnt for fstream, I thought fstream is both ofstream and ifstream combined.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

See https://en.cppreference.com/w/cpp/io/basic_fstream for an example.

You need to "rewind" the file to read just written stuff (s.seekp(0);).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading