Aan
Aan

Reputation: 12890

Ofstream doesn't work well?

In this code, fout is an ofstream object, It supposes to write to a file called output.txt. For a reason output.txt always empty!. I would ask about the mistake I did in the code :

#include<iostream>
#include<fstream>
#include<stdio.h>//to pause console screen
using namespace std;

double Volume(double);

int main() {
    ifstream fin; //read object
    ofstream fout;// writing object
    double Radius;
    fin.open("input.txt");
    fout.open("output.txt");
    if(!fin){
        cout<<"There a problem, input.txt can not be reached"<<endl;
    }
    else{
fin>>Radius;
fout<<Volume(Radius);
cout<<"Done! check output.txt file to see the sphare volume"<<endl;
    }

    getchar();//to pause console screen
return 0;
}

double Volume(double r){

double vol;
vol= (4.0/3.0)*3.14*r*r*r;
return vol;
}

Upvotes: 1

Views: 4254

Answers (3)

theck01
theck01

Reputation: 203

You have to flush the stream, call fout.flush() after you are done outputting, all you are doing is building a buffer that has yet to be written to the file. flush actually puts the buffer into the file.

Upvotes: 3

Robᵩ
Robᵩ

Reputation: 168626

"output.txt always empty"

I suspect that you are not allowing fout to flush its output. Do either of these statements apply to you?

  • You check the contents of "output.txt" after the getchar() is invoked, but before the program ends?

  • You end the program with a Ctrl+C?

If so, you have not allowed the data to be written to fout. You can solve this problem by avoiding those two conditions, or doing one of these:

  • Add fout << endl after you write your data, or

  • Add fout << flush after you write your data, or

  • Add fout.close() after you write your data.

Upvotes: 5

hmjd
hmjd

Reputation: 121971

In addition to calling fout.flush() you could change:

fout<<Volume(Radius);

to

fout<<Volume(Radius) << std::endl; // Writes a newline and flushes.

or you can close the stream fout.close() if it is no longer required.

Upvotes: 1

Related Questions