I’m having a problem creating a ifstream with a filename which isn’t defined at compile time. The following example works fine:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string file, word;
int count = 0;
cout << "Enter filename: ";
cin >> file;
ifstream in("thisFile.cpp");
while(in >> word)
count++;
cout << "That file has " << count << " whitespace delimited words." << endl;
}
But if I change the line ifstream in("thisFile.cpp"); to ifstream in(file); I get a compile error. Why is this?
File streams in C++98 only take C-style character strings for the constructor argument, not C++ strings, an oversight in the C++98 standard that was corrected in the C++11 update. If your compiler doesn’t support C++11 yet, you can open a file from a string name by simply calling
c_str()to get a C-style character pointer out of a C++ string: