Creating Files with String filenames

I can't get c++ compilers to create or open files with a string input, even though the compiler accepts a file name in "quotes". How can I get this compiled (I am downloading a series of file names which I need to load into a consolidated file).

My coding (the commented line works, the string example does not).

Any help would be appreciated.

//indirect file open example
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(void)

{
string myfile="VUSTX.CSV";
ifstream(myfile);
// ifstream("VUSTX.CSV");

return 0;
}

Compile in C++11 mode, or use myfile.c_str() instead of just myfile.
Yes! It works - Why?

Where to get C++11 mode compiler?

Thanks!

G.
If you're using an IDE to compile, look for an option to enable C++11.

If you're compiling on the command line using g++ (or similar), add the -std=c++11 option.

It works because the constructor takes a const char* as argument (basically, a C string), and while a string literal like "filename.txt" satisfies that, a std::string does not.
However, you can call the c_str() member function, which returns a C string with the contents of the string, and pass that to your ifstream object.
Thanks for your help.

I'm starting with C++ after many years with Pascal (alas being phased out and without good 64 bit support), as well as 35 years programming in basic/Mumps/Z-80 (and essentially 80/80 assembler).

C++ is a little strange to me, but I assume it has advantages since it has essentially replaced all my previous languages.

But I'll persevere - all my other languages were self taught, so why not this one?

G.
Topic archived. No new replies allowed.