Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use c_str() in functions [duplicate]

I am reading the book C++ Primer and at the file input output chapter it uses:

ifstream infile(ifile.c_str());

to open a file whose name is in the string ifile.

I tried the code and it works perfectly even without c_str(). So what is the point of using it?

Should I use c_str() when I am trying to open a file from a command line argument? I mean which is the correct usage:

ifstream fin( argv[1] )

or

ifstream fin( argv[1].c_str() )
like image 986
hyperknot Avatar asked Jun 18 '11 13:06

hyperknot


1 Answers

The constructor for ifstream used to only take a const char * (which is what the c_str() method provides.

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

It could also be specific to your implementation.

like image 62
jonsca Avatar answered Nov 16 '22 00:11

jonsca