Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}      
like image 946
ToM MaC Avatar asked Jan 27 '16 19:01

ToM MaC


2 Answers

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?

like image 68
NathanOliver Avatar answered Oct 21 '22 16:10

NathanOliver


Your constructor ofstream entrada(asegurado,"");, does not match that for std::ofstream. The second argument needs to be a ios_base, see below:

entrada ("example.bin", ios::out | ios::app | ios::binary);
                            //^ These are ios_base arguments for opening in a specific mode.

To get your program running you simply need to remove the string literal from your ofstream constructor:

ofstream entrada(asegurado);

See the live example here.

If you are using c++03 or lower then you cannot pass a std::string to the constructor of ofstream you will need to pass a c string:

ofstream entrada(asegurado.c_str());
like image 45
Fantastic Mr Fox Avatar answered Oct 21 '22 16:10

Fantastic Mr Fox