Rick_Sch
Rick_Sch

Reputation: 456

C++ - Simple ifstream error

Could anyone help me figure out who the lime with ifstream myfile(fileName); is generating an error upon compilation with g++?

string fileName;

cout << "\nPlease enter the name of your input file:" << endl;
cout << "->";
getline (cin, fileName);

cout << "fileName: " << fileName << endl;

string line;
ifstream myfile(fileName);
if (myfile.is_open()){
    while(getline(myfile, line)){
        cout << line << endl;
    }
myfile.close();
} else {
    cout << "Unable to open file"; 
}

Upvotes: 0

Views: 202

Answers (2)

david
david

Reputation: 580

You need to convert it to a c-string first.

Try myfile((filename).c_str())

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227608

Unless you have C++11 support, you need to pass a const char* to the constructor. You can achieve it like this:

std::ifstream myfile(fileName.c_str());

See this documentation for the relevant constructors.

Upvotes: 4

Related Questions