如何在不输入“.txt”的情况下保存文本文件?

时间:2011-03-22 14:58:30

标签: c++

我的程序(c ++):

#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”。我怎么能这样做?

1 个答案:

答案 0 :(得分: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.
}