Why should I use c_str () in functions

I read the C ++ Primer book and in the chapter on inputting the output of the file it uses:

ifstream infile(ifile.c_str()); 

to open the file whose name is in the ifile line.

I tried the code and it works fine even without c_str() . So what is its meaning?

Should I use c_str() when I try to open a file from a command line argument? I mean this is the correct use:

 ifstream fin( argv[1] ) 

or

 ifstream fin( argv[1].c_str() ) 
+7
source share
3 answers

The constructor for ifstream uses only const char * (this is what the c_str() method c_str() .

I believe there is a new constructor for it that accepts std::string in the upcoming standard, (edit) see this answer .

It may also be specific to your implementation.

+15
source

This book is pretty old (at least the issue I have is pretty old and maybe yours too). The iostream library is much older than STL and the string class; earlier vrsions iostream didn't have a string constructor, that's all.

+6
source
Constructor

ifstream takes the file name as const char * , not a C ++ string . See this . The c_str() member c_str() returns a const char * pointer to a string.

edit: Perhaps your compiler supports an overloaded version of this constructor or an updated standard.

+2
source

All Articles