This is for the more experienced folks.

Recently I found that in Visual C++ 2010 (and 2012, not sure about earlier versions) one can use a std::string as the file name argument for the .open( ) function. I've always known the .open( ) function to take only char* (C-style) strings as the argument. Use of std::string would require the use of the .c_str( ) method.

Anyone have any idea when this showed up in VC++? And why MS doesn't seem to document it?

Example code

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main ()
{
    string fname = "test.txt";
    ifstream fin;

    fin.open( fname );    //previously, this had to be: fin.open( fname.c_str( ) );

    if( ! fin )
        cout << "Error." << endl;

    fin.close( );

    return 0;
}

Recommended Answers

All 5 Replies

I'm pretty sure the std::string overload was added in C++0x. I can only imagine they didn't add it earlier o prevent a dependancy between the <string> and <fstream>. I haven't been able to find an official statement about why they made the choice to add it in C++0x, although I'm sure it somewhere..

Section 27.9.1.4 of a 2010 draft of the C++0x standard (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf) contains the function declaration.

Well, you could probably go through the minutes of the committee meetings, but I think in this case the rationale is pretty obvious. It's closing an consistency hole in the standard library where there's not an overload for both C-style strings and C++ strings.

I don't use VS at the moment, but is it still backwards compatible? Can I still give a c-style-string to .open()?

Can I still give a c-style-string to .open()?

Of course. Support for std::string was added as an overload.

I think I'll stick with the use of c_str() for the time being. Ill wait till c++0x becomes more widespread.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.