mikithskegg
mikithskegg

Reputation: 816

File stream constructor

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?

Upvotes: 0

Views: 277

Answers (2)

shuttle87
shuttle87

Reputation: 15934

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.

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361412

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

Upvotes: 2

Related Questions