简体   繁体   中英

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

i am trying to create a file whose name is tied to a string type variable, however when i try to run it, i get this error --[Error] no match for call to '(std::ofstream {aka std::basic_ofstream}) (const char*)'

Here is the code:

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());
}

In this statement:

output(nombre.c_str());

The compiler thinks that output is a "callable" but std::fstream didn't overload call operator. So you get compile-time error.

To fix it; you either call the member open :

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

or when initializing output :

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

You should use the output operator for ostream when you need to output something:

output << nombre;

Anyway, your ofstream output; is not associated with any filename.

Update: looks like the intention was to assign the filename to the fstream . In this case look to the answer of @ItachiUchiwa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM