2011-03-22 84 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