2014-01-20 58 views
3

我有這個代碼在C + +工作得很好,首先它要求用戶輸入 文件名,然後在該文件中保存一些數字。文件setprecision C++代碼

但是我試圖做的是有兩位小數,e.g的 用戶類型2保存號碼,我想保存號碼2,但保留兩位小數 2.00

任何想法如何做到這一點?

#include <iostream> 
#include <fstream> 
#include <iomanip> 
using namespace std; 

int main() { 
    double num; 
    double data; 
    string fileName = " "; 
    cout << "File name: " << endl; 
    getline(cin, fileName); 
    cout << "How many numbers do you want to insert? "; 
    cin >> num; 
    for (int i = 1; i <= num; i++) { 
    ofstream myfile; 
    myfile.open(fileName.c_str(), ios::app); 
    cout << "Num " << i << ": "; 
    cin >> data; 
    myfile << data << setprecision(3) << endl; 
    myfile.close(); 
    } 
    return 0; 
} 
+3

爲什麼在寫入data之後使用'setprecision()'*? – nobar

+3

@nobar:你可能應該回答這個問題,因爲這幾乎肯定是問題所在。 – PeterK

+0

我不知道,只是試圖找到一種方法來做到這一點:/ – user3214262

回答

7

好的,在寫入數據之前,您需要使用setprecision

我也會將文件的打開和關閉移出循環(當然,因爲它通常是一個相當「沉重」的操作來打開和關閉像這樣的循環內的文件的聲明myfile

這裏有一個小演示的作品:但是

#include <iostream> 
#include <fstream> 
#include <iomanip> 

int main() 
{ 
    std::ofstream f("a.txt", std::ios::app); 
    double d = 3.1415926; 

    f << "Test 1 " << std::setprecision(5) << d << std::endl; 

    f << "Test 2 " << d << std::endl; 

    f << std::setprecision(7); 
    f << "Test 3 " << d << std::endl; 

    f.precision(3); 
    f << "Test 3 " << d << std::endl; 

    f.close(); 


} 

需要注意的是,如果你的數量例如爲3.0,那麼你還需要std::fixed例如,如果我們這樣做:

f << "Test 1 " << std::fixed << std::setprecision(5) << d << std::endl; 

它會顯示3.00000

+0

ofstream myfile; (i = 1; i <= num; i ++) cout <<「Num」<< i <<「:」; (2); std :: cout << std :: setprecision(3)<< endl; cin >> data; myfile << data << endl; } myfile.close(); 我修改我的代碼,現在看起來像這樣,但我仍然是一樣的:/ – user3214262

+0

@ user3214262'setprecision()'是特定於流的。如果你希望它適用於'myfile',你必須將它應用於'myfile',而不是'std :: cout'。 – Angew

+0

謝謝Mats Petersson – user3214262