Search code examples
c++stringofstream

no matching function for call to `std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&)'


I am trying to write a program that ask the user for a file name and then it opens that file. When I compile it I get the following error:

no matching function for call to std::basic_ofstream<char, 
std::char_traits<char> >::basic_ofstream(std::string&)

This is my code:

using namespace std;

int main()
{ 
    string asegurado;
    cout << "Nombre a agregar: ";
    cin >> asegurado;

    ofstream entrada(asegurado,"");
    if (entrada.fail())
    {
        cout << "El archivo no se creo correctamente" << endl;
    }
}      

Solution

  • std::ofstream can only be constructed with a std::string if you have C++11 or higher. Typically that is done with -std=c++11 (gcc, clang). If you do not have access to c++11 then you can use the c_str() function of std::string to pass a const char * to the ofstream constructor.

    Also as Ben has pointed out you are using an empty string for the second parameter to the constructor. The second parameter if proivided needs to be of the type ios_base::openmode.

    With all this your code should be

    ofstream entrada(asegurado); // C++11 or higher
    

    or

    ofstream entrada(asegurado.c_str());  // C++03 or below
    

    I also suggest you read: Why is “using namespace std;” considered bad practice?