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;
}
}
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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With