Why should I use c_str() in functions
Solution 1
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.
Solution 2
That book is rather old (at least, the edition I have is rather old, and perhaps yours, too.) The iostream
library is much older than STL and the string
class; earlier vrsions of iostream
didn't have the string
constructor, that's all.
Solution 3
ifstream
constructor takes filename as a const char *
rather than a C++ string
. See this. The c_str()
member function returns a const char *
pointer to the string.
edit: Maybe your compiler supports an overloaded version of this constructor or the standard got updated.
hyperknot
I'm Zsolt Ero, a creative full-stack developer from Budapest, Hungary. I enjoy working with interactive maps and creating augmented reality apps. I'm the founder of MapHub (https://maphub.net/) and I'm also available for freelance work.
Updated on June 04, 2022Comments
-
hyperknot about 2 years
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() )
-
Armen Tsirunyan about 13 yearsnot
char*
...const char*
there's a huge difference -
N.R.S.Sowrabh about 13 yearsyes, but I thought maybe the emphasis here is on the
char *
part of it. -
Armen Tsirunyan about 13 yearsThanks :) Now my soul is at peace :)
-
David Rodríguez - dribeas about 13 years+1 The latest copy of the upcoming standard document, which is a Final Draft (no semantic changes should be performed in the document prior to the approved standard) does have a constructor that takes a `const std::string&)
-
jonsca about 13 years@David Thanks for the info! I'm behind on my reading :)