Ofstream不能很好用吗?

Aan*_*Aan 1 c++ fstream file

在这段代码中,fout是一个ofstream对象,它假设写入一个名为的文件output.txt.因为一个output.txt总是空的原因!我会问我在代码中犯的错误:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 5

"output.txt总是空的"

我怀疑你不允许fout刷新它的输出.这些陈述中的任何一个都适用于您吗?

  • getchar()调用之后但在程序结束之前检查"output.txt"的内容?

  • 你用Ctrl+ 结束程序C

如果是这样,您就不允许写入数据fout.您可以通过避免这两个条件或执行以下任一操作来解决此问题:

  • fout << endl在您编写数据后添加,或

  • fout << flush在您编写数据后添加,或

  • fout.close()写完数据后添加.