2011-11-30 58 views
1

在此代码中,fout是一个ofstream对象,它假定写入一个名为output.txt的文件。为什么output.txt总是空的!我想请教一下这个错误我在代码中所做的:Ofstream不能正常工作?

#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; 
} 
+2

缓冲。在调用'getchar()'之前调用'fout.flush()'来刷新它,并且你很好。 – 2011-11-30 20:48:44

回答

5

“output.txt的总是空的”

我怀疑你是不是允许fout刷新其输出。这些陈述中的任何一条适用于您?

  • 选中“output.txt的”的内容getchar()后 调用,但该程序结束之前?

  • 您结束与按Ctrl +ç程序?

如果是这样,您不允许将数据写入fout。您可以通过避免这两个条件,或做其中的一个解决这个问题:

  • 添加fout << endl你写你的数据后,或

  • 添加fout << flush你写你的数据后,或

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

+0

看起来不错。我懒得写它,但我添加了一个花哨的Ctrl + C按钮给你:) +1 – 2011-11-30 21:01:50

3

你必须冲洗流,叫fout.flush()你完成输出之后,你正在做的是建立一个尚未被写入缓冲区文件。 flush实际上将缓冲区放入文件中。

+1

文件流在关闭时会自动刷新,包括在销毁时隐式关闭文件流。 –

+0

@Rob:对。但他正在调用'getchar()'来阻塞程序,直到某个终端输入。因此缓冲区在检查文件时保持不刷新状态。 – 2011-11-30 20:54:49

+0

@ VladLazarenko同意,看我的答案。关键是“从未写入文件”是误导性的。 –

1

除了呼吁fout.flush()你可以改变:

fout<<Volume(Radius); 

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

,或者您可以关闭流fout.close()如果不再需要。

+0

提及'ofstream :: close()'+1。我认为当文件不再需要打开时应该始终调用它。无论如何,文件都会被关闭,但明确地做文件会更好,因为它会记录您的意图。 –