2017-07-06 20 views
-1

當我有用戶輸入一個段號碼(如1.1,3.4,4.23等),我需要能夠節號寫爲.txt文件,是包括1.0,其中當前1.0被寫爲整數1(或者被寫爲1.1的1.10)。FileIO專注,寫入文件,VAR = 1.0變爲1

這樣做是一堆「如果」語句凌亂,有沒有更好的辦法?

編輯:

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

int main() 
{ 
    cout << "Enter a float here" << endl; 
    float f; 
    cin >> f; 

    ofstream fine; 
    fine.open("fine.txt", ios::out); 
    fine << f << "\n"; 
} 

如果輸入1.0作爲浮動,這樣可以節省1到.TXT。我需要做的是讓用戶輸入一個像1.0或1.10這樣的數字,然後讓它們按照原樣寫入.txt,而不是截斷零。

+0

可以顯示用於寫入文件的代碼嗎? – user0042

+0

[mcve]。不要讓我們猜測你的實現是什麼樣子。 –

+1

如果不知道您的約束條件,我們無法猜測出正確的解決方案。部分號碼的有效格式是什麼?你想執行驗證嗎?如何將錯誤的輸入(例如1.10)翻譯成好的輸入(例如1.1)?你需要成爲_specific_。 –

回答

6

float是可怕的選擇來表示一個「節號」。如果您使用float則§1.1==§1.10和§1.3.2不能存在。請嘗試使用std::string代替:

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 
using namespace std; 

int main() 
{ 
    cout << "Enter a section number here" << endl; 
    string f; 
    cin >> f; 

    ofstream fine; 
    fine.open("fine.txt", ios::out); 
    fine << f << "\n"; 
}