The simple problem you are having here is that the variable filename
that stores the name of the file is of type char
. Change it to string
so that it works.
On another note, try to break down the error message you got:
no matching function for call to 'std::basic_ofstream::open(std::__cxx11::string&, const openmode&)'
In open(std::__cxx11::string& ...
it clearly says that the data type of the file name should be string&
. This indicated that you had a data type error, which is true because you have used char
instead of string
.
Another thing: use char only when you want to accept a single letter as input; when you want to take a word or a sentence, store it in a string variable, and get it from the user using the getline()
function. This will make your life easier.
To modify your code, firstly change your variable declaration statement to:
string fileName; // std:: is not required as you have the line "using namespace std"
Secondly, change the input statement of the file name from cin >> filename;
to:
getline(cin, fileName);
It should work after these changes.
EDIT: I found the peoblem to your question. You will nave to change the open command to:
myFile.open(fileName.c_str(), ios::out);
Like it says in the error, the function needs a string passed to ot, however, when we take the string as input and store it in the variable fileName, it simply converts the string into a const char *. This is invisible to you when you run the code, but every once in a while, it causes an error.
This should definitely work now.