0

File stream class cannot accept string as argument of its construtor, only C-string.

char fname[] = "file";
string fname_string ("file");
ifstream ifs (fname); //OK
ifstream ifs (fname_string); //Error

Why is it so? Is there any sense in that?

mikithskegg
  • 806
  • 6
  • 10

2 Answers2

2

Because in C++03, std:istream doesn't have a constructor which takes std::string as argument. However, in C++11, it has!

So as long as you use C++03, you've to do this:

std::ifstream ifs (fname_string.c_str()); //Ok in C++03 and C++11 both!

Only in C++11, you can do this:

std::ifstream ifs (fname_string); //Ok in C++11 only
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Of course, I know that. But why? Why the authors of the C++ Stream Library did not created constructor with string as argument? – mikithskegg Feb 19 '12 at 12:09
  • 1
    Yes, it must be the only reason ))) – mikithskegg Feb 19 '12 at 12:10
  • @mikithskegg: You can see this topic created by me : [Design of std::ifstream class](http://stackoverflow.com/questions/4640281/design-of-stdifstream-class) – Nawaz Feb 19 '12 at 12:13
2

If you want to pass a object of std::string you should use the .c_str() member function. This will convert it to an old style string.

The ifstream constructor only takes the old style strings. I'm guessing that ifstream probably doesn't allow implicit conversions because it could make a bunch of annoying hassles occur when objects that really don't represent filename strings get converted implicitly.

shuttle87
  • 15,466
  • 11
  • 77
  • 106