72

I have:

string filename: 
ifstream file(filename);

The compilers complains about no match between ifstream file and a string. Do I need to convert filename to something?

Here's the error:

error: no matching function for call to ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)’
/usr/include/c++/4.4/fstream:454: note: candidates are: std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]
3
  • 1
    I'm sure you could improve the title of this question. Commented Jun 12, 2011 at 18:12
  • I changed it to ifstream error.
    – Mark
    Commented Jun 12, 2011 at 18:13
  • That's still incredibly vague. Can't you make it so that it actually describes the specific issue? Commented Jun 12, 2011 at 18:34

3 Answers 3

144

Change

ifstream file(filename);

to

ifstream file(filename.c_str());

Because the constructor for an ifstream takes a const char*, not a string pre-C++11.

1
  • 2
    "love" c++ so much! Commented Apr 30, 2019 at 3:36
11

The ifstream constructor expects a const char*, so you need to do ifstream file(filename.c_str()); to make it work.

1

in c++-11 it can also be an std::string. So (installing c++-11 and) changing the dialect of you project to c++-11 could also fix the problem.

1
  • 1
    while your answer is correct, it is already present in the accepted answer, although not so clearly: not a string pre-C++11.
    – Chris Maes
    Commented Jan 6, 2016 at 8:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.