How to input a file name using a string?

Howdy guys,

Hopefully my first forum post isn't too ambiguous, but I've searched for some time now across the web, and can't find anything. Basically I want to create a new text file to hold some, you guessed it, text, but I want to be able to have the name of the file predetermined in a string. However, I'm apparently not allowed to do that, and I have to write out the name of the file upon creation (the commented section of code is what "allowed"). If I try to compile, I get an error that goes along the lines of "no matching function for call to 'std::basic_ofstream<char, std::char_traits......". Sorry if this doesn't make any sense, I'm a pretty hardcore newbie (just started coding about a week and a half ago). If there is a better way to do this, please let me know.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{

    string myFileName = "myFileTest.txt";

    ofstream myfile;
    myfile.open (/*"theRightWayToCreateAFile.txt"*/myFileName);
    myfile << "This is my text in the file called:" << myFileName;
    myfile.close();

    return 0;
}

Thanks for taking the time to read and possibly respond to my post!

Cheers
try myfile.open(myFileName.c_str());
Last edited on
New C++ Standard allows to use argument of type std::string in the member function open. Howevver not all compilers support this new feature.
Thanks CJC0117, worked like a charm.
Topic archived. No new replies allowed.