C++ ifstream error using string as opening file path.

C++Ifstream

C++ Problem Overview


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>]

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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

Solution 3 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkView Question on Stackoverflow
Solution 1 - C++Seth CarnegieView Answer on Stackoverflow
Solution 2 - C++Alexander GesslerView Answer on Stackoverflow
Solution 3 - C++evi vView Answer on Stackoverflow