WhiteHotLoveTiger
WhiteHotLoveTiger

Reputation: 2228

Create ifstream with user generated filename?

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?

Upvotes: 1

Views: 1597

Answers (3)

Ross Smith
Ross Smith

Reputation: 3765

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:

ifstream in(file.c_str());

Upvotes: 4

robert
robert

Reputation: 34408

You need the c_str method:

ifstream in(file.c_str());

Upvotes: 2

jcoder
jcoder

Reputation: 30035

before c++11 the ifstream constructor only took a const char* not a string for the filename.

So try ifstream in(file.c_str()); instead

Upvotes: 3

Related Questions