0

谁能帮我找出谁是ifstream myfile(fileName); 使用 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"; 
}
4

2 回答 2

4

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.

于 2012-11-05T19:46:06.130 回答
1

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

Try myfile((filename).c_str())

于 2012-11-05T19:46:40.480 回答