ofstream .open() wont open a file

Im trying have have a user specify a filename that they want to open but for some reason it wont allow me to put a simple string varible in as a param for File.open(filename);

I get this error
1
2
error: no matching function for call to 'std::basic_ofstream<char, std::char_traits<char> >::open(std::string&)'|
note: candidates are: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]|


This is what i am trying to do
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void newchar(){
    string filename;
    ofstream File;

    cout << "Enter desired character name:";
    cin >> filename;

//Imagine whatever the filename is has .txt at the end

    File.open(filename);
    File << filename;
    File << 1;
    File << 100;
    File << 5;
    File << 10;
    File << 0;
    File.close();
}


Also is it possible to do File.open(filename".txt");
Last edited on
Passing a std::string to open is allowed in C++11. To concatenate two string you can use the + operator.
File.open(filename + ".txt");

In older compilers you will have to pass a C string (char*). You can use c_str() to get a C string from a std::string:
File.open(filename.c_str());

File.open((filename + ".txt").c_str());
Last edited on
Topic archived. No new replies allowed.