9

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;
    }
}      
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
ToM MaC
  • 93
  • 1
  • 1
  • 3

2 Answers2

19

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?

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • I dont think this is the case. It still fails for c++14 http://ideone.com/PVylpo, the problem is that there is no constructor that takes a string literal as the second argument. – Fantastic Mr Fox Jan 27 '16 at 19:08
  • Thank you so much! but where in the code will be the function `c_str()` ? I never used it before. – ToM MaC Jan 27 '16 at 19:11
  • @ben That is why I answered as I did. I did point out the typo as well with attribution to you. – NathanOliver Jan 27 '16 at 19:15
  • Ok, answers all scenarios +1. – Fantastic Mr Fox Jan 27 '16 at 19:17
  • I did it, i just added the function `c_str()` to `ofstream entrada(asegurado); and it works fine, now i'll read why is using namespace std;" considered bad practise. Thank you very much for everything! Grats – ToM MaC Jan 27 '16 at 19:22
1

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());
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175