7

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() )
Nick Dandoulakis
  • 42,588
  • 16
  • 104
  • 136
hyperknot
  • 13,454
  • 24
  • 98
  • 153

3 Answers3

16

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.

Community
  • 1
  • 1
jonsca
  • 10,218
  • 26
  • 54
  • 62
  • 2
    +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&) – David Rodríguez - dribeas Jun 18 '11 at 13:43
7

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.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
2

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.

Community
  • 1
  • 1
N.R.S.Sowrabh
  • 725
  • 13
  • 30