Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

ifstream

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>] 
like image 389
Mark Avatar asked Jun 12 '11 18:06

Mark


People also ask

Why is ifstream not Opening file C++?

The issue is most likely one of the following: 1) map_2. txt does not exist in the location you specified in your ifstream declaration. 2) You do not have sufficient rights to access the root folder of your C drive.

Does ifstream open a file?

std::ifstream::open. Opens the file identified by argument filename , associating it with the stream object, so that input/output operations are performed on its content. Argument mode specifies the opening mode. If the stream is already associated with a file (i.e., it is already open), calling this function fails.

How do I declare ifstream?

A construction statement for the second syntax is as follows: ifstream ifs = ifstream("dir1/txtFile. txt", ios_base::in); The name of the file whose content is to be read is, “txtFile.


1 Answers

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.

like image 199
Seth Carnegie Avatar answered Nov 15 '22 09:11

Seth Carnegie