User defined output file name

I am trying to write a program that will output whatever the user types in to a file with the name of thier choice. If I give it a specific name I can run the program and it out puts fine, but if I write in a string variable it doesn't work. This is the error I get :

20 C:\Users\Phil\Desktop\Programing\C++\Base.cpp no matching function for call to `std::basic_fstream<char, std::char_traits<char> >::open(apstring&, const std::_Ios_Openmode&)'

this is the code I am running when I get the error. I have bolded the part where the error occurs.


#include <iostream.h>
#include <conio.h>
#include "apstring.h"
#include <iomanip.h>
#include <fstream.h>
#include <cstdlib>

main()
{

fstream outfile;

apstring user, filename;
int a = 1;
filename = "Hello.txt";

outfile.open(filename, ios::out);
if (outfile)
{
do
{
getline(cin, user);
if (user == "done")
break;
outfile << user << endl;
}
while (a != 2);
}
else
cout << "An error occured.";

return 0;
}

If I change the code to look like this in the area of the error it works fine.

outfile.open("Hello.txt", ios::out);

I don't understand why I can't use a variable. I tried having it as a user input for what the variable filename is equal to but that didn't work so I changed it to a constant. I have been playing with using the char type and stuff to no avail. Does anyone know why this doesn't work?
The open function takes a C string (const char*) as argument. In C++11 it also works with std::string.

You can use the c_str() member function to convert an apstring to a C string
outfile.open(filename.c_str(), ios::out);
Last edited on
Thanks that worked perfectly.
Topic archived. No new replies allowed.