2011-11-30 51 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。我認爲當文件不再需要打開時應該始終調用它。無論如何,文件都會被關閉,但明確地做文件會更好,因爲它會記錄您的意圖。 –