Why should I use c_str() in functions

16,044

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.

Share:
16,044
hyperknot
Author by

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, 2022

Comments

  • hyperknot
    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
    Armen Tsirunyan about 13 years
    not char* ... const char* there's a huge difference
  • N.R.S.Sowrabh
    N.R.S.Sowrabh about 13 years
    yes, but I thought maybe the emphasis here is on the char * part of it.
  • Armen Tsirunyan
    Armen Tsirunyan about 13 years
    Thanks :) Now my soul is at peace :)
  • David Rodríguez - dribeas
    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
    jonsca about 13 years
    @David Thanks for the info! I'm behind on my reading :)