2011-03-22 50 views
2

我的計劃(C++):如何保存文本文件而不在末尾鍵入「.txt」?

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

float x, y, z; 
char d[20]; 

int main() 
{ 
    cin.getline >>d; 
    x=111; 
    y=222; 
    z=333; 
    ofstream meuarquivo; 
    meuarquivo.open (d".txt"); 
    meuarquivo << x << "\n"; 
    meuarquivo << y << "\n"; 
    meuarquivo << z << "\n"; 

    meuarquivo.close(); 

    return 0; 
} 

我想寫類似「ThatsMyProgram」,我想程序將此文件保存爲「ThatsMyProgram.txt」。我怎樣才能做到這一點?

+0

有沒有你正在使用一個char []爲保持輸入,你能不能從標準庫使用字符串什麼特別的原因? – DaveJohnston 2011-03-22 15:05:42

回答

5

使用std::string,這對於級聯定義operator +

#include <iostream> 
#include <fstream> 
#include <cstdlib> 
#include <string> 

int main() 
{ 
    std::string filename; 
    std::getline(std::cin, filename); 

    std::ofstream file((filename + ".txt").c_str()); 

    // use stream here. 
} 
+0

Victor,ofstream的構造函數不接受'std :: string' – Nawaz 2011-03-22 15:05:00

+4

不幸的是,您需要'std :: ofstream文件((filename +「.txt」)。c_str())'。 – 2011-03-22 15:07:00

+0

即將用C++ 0x修復。一些編譯器已經有了。 – 2011-03-22 15:58:43

相關問題