1. Note that the C++11 version of fstream::open() does have an overload that accepts string, so with new compilers you won't have a problem. (Do you which compiler and version you're using?)
(Edit: 2 is just repeating part of what IWishIKnew said...)
2. Before that, you just need to use string::c_str() to get hold of a const char* pointer to the contained string.
(assuming usual includes...)
string filename;
(ask user for file name storing it in string...)
1 2 3
|
ifstream myfile2; //Creating myfile2
myfile2.open(filename.c_str()); //Calling a function contained by myfile2
// now using .c_str();
|
(The ios::in (or std::ios::in) parameter in IWishIKnew's example is optional; this flag is implicit when using an ifstream, as opposed to opening an fstream in read mode.)
3. IWishIKnew's approach, using the constructor which takes the filename and opens the file, is better form than using the default constructor and then opening explicitly.
4 This is not good code :-(
1 2 3 4
|
char input[100];
cin >> input;
ifstream myfile2;
myfile2.open(input);
|
because cin >> does not care how many chars you give it to extract into your array. So you could overrun if given a stupidly large file name. If for some reason you need to use a buffer, use istream::get() instead:
http://www.cplusplus.com/reference/istream/istream/get/
1 2 3
|
char input[100];
cin.get(input, 100); // get up to 100 chars
ifstream myfile2(input);
|
5. I agree with IWishIKnew that the new an array, memcpy, etc approach is TERRIBLE!
Andy