简体   繁体   English

Ofstream效果不好?

[英]Ofstream doesn't work well?

In this code, fout is an ofstream object, It supposes to write to a file called output.txt . 在此代码中,fout是一个ofstream对象,它假定写入一个名为output.txt的文件。 For a reason output.txt always empty!. 由于某种原因, output.txt始终为空!。 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;
}

"output.txt always empty" “ output.txt始终为空”

I suspect that you are not allowing fout to flush its output. 我怀疑您不允许fout刷新其输出。 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? 您在调用getchar()之后但在程序结束之前检查“ output.txt”的内容吗?

  • You end the program with a Ctrl + C ? 您以Ctrl + C结束程序吗?

If so, you have not allowed the data to be written to fout . 如果是这样,则您不允许将数据写入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 写入数据后添加fout << endl ,或者

  • Add fout << flush after you write your data, or 写入数据后添加fout << flush ,或者

  • Add fout.close() after you write your data. 写入数据后,添加fout.close()

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. 您必须刷新流,在完成输出后调用fout.flush() ,您所做的只是建立一个尚未写入文件的缓冲区。 flush actually puts the buffer into the file. flush实际上将缓冲区放入文件中。

In addition to calling fout.flush() you could change: 除了调用fout.flush()您还可以更改:

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. 或者,如果不再需要流fout.close()则可以将其关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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