0
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;
int main(){
    ofstream file;
    string nameclass;
    cin>>nameclass;
    file.open(nameclass);
return 0;
}
The compiler says:
10  21  [Error] no matching function for call to 'std::basic_ofstream<char>::open(std::string&)'
716 7   C:\Program Files (x86)\Dev-Cpp\MinGW64\lib\gcc\x86_64-w64-mingw32\4.9.2\include\c++\fstream [Note] void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
716 7   C:\Program Files (x86)\Dev-Cpp\MinGW64\lib\gcc\x86_64-w64-mingw32\4.9.2\include\c++\fstream [Note] no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'const char*'
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Teo
  • 45
  • 4
  • 1
    This is an interesting piece of code and an interesting compiler message. But what is your *question*? Did you *understand* the error message? What did you think it was trying to tell you? What happened when you copied and pasted the interesting looking parts of it - like, say, `no known conversion for argument 1 from 'std::string`, or `no matching function for call to 'std::basic_ofstream::open(std::string&)'` - into a search engine? – Karl Knechtel Mar 24 '21 at 11:25
  • 1
    Does this answer your question? [no matching function for call to \`std::basic\_ofstream >::basic\_ofstream(std::string&)'](https://stackoverflow.com/questions/35045781/no-matching-function-for-call-to-stdbasic-ofstreamchar-stdchar-traitscha) That was the first result for me when I [tried that](https://duckduckgo.com/?q=no+matching+function+for+call+to+%27std%3A%3Abasic_ofstream%3Cchar%3E%3A%3Aopen(std%3A%3Astring%26)%27). – Karl Knechtel Mar 24 '21 at 11:27

1 Answers1

1

This is because, until , the function std::ofstream::open() is expecting a const char * instead of a std::string.
Fortunately, std::string already have a member function that converts the string into a const char * std::string::c_str().

Replace:

file.open(nameclass);

With:

file.open(nameclass.c_str());

And it should work :)

That being said, if you really want to pass a std::string directly, you will have to activate support (at least) in your compilation options.

Fareanor
  • 5,900
  • 2
  • 11
  • 37