C ++ ifstream error, using a string as a path to open a file.

I have:

string filename: ifstream file(filename); 

Compilers complain about the lack of correspondence between the ifstream file and the string. Do I need to convert a file name 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>] 
+58
c ++ ifstream
Jun 12 '11 at 18:08
source share
3 answers

Edit

 ifstream file(filename); 

to

 ifstream file(filename.c_str()); 

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

+117
Jun 12 '11 at 18:09
source share

ifstream constructor expects const char* , so you need to do ifstream file(filename.c_str()); so that it works.

+10
Jun 12 '11 at 18:09
source share

in C ++ - 11 it can also be std :: string. Therefore (installing C ++ - 11 and) changing the dialect of your project in C ++ - 11 can also fix the problem.

+1
Jan 05 '16 at 20:17
source share



All Articles