fstream 库,试图创建一个具有变量名的文件 (c++)

fstream library, trying to create a file with variable name (c++)

我正在尝试创建一个名称与字符串类型变量相关联的文件,但是当我尝试 运行 它时,出现此错误 --[错误] 不匹配调用 '( std::ofstream {aka std::basic_ofstream}) (const char*)'

代码如下:

void Crear()
{   
    string nombre;
    ofstream output;
    ifstream input;

    cout << "Deme el nombre de su archivo: ";
    cin.ignore();
    getline(cin, nombre);

    //this is where the error happens
    output(nombre.c_str());
}

在此声明中:

output(nombre.c_str());

编译器认为 output 是 "callable" 但 std::fstream 没有重载调用运算符。所以你会得到编译时错误。

修复它;你要么打电话给会员 open:

    output.open(nomber); // directly because the new standard allows strings for fstream::open

或者初始化时output:

std::ofstream output(nombere); // (contructor of ofstream that takes std::string) or 
std::ofstream output(nombere.c_str()); // ctor that takes const char*