C ++ - 简单的ifstream错误

时间:2012-11-05 19:43:44

标签: c++ ifstream

有没有人可以帮我弄清楚谁用 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"; 
}

2 个答案:

答案 0 :(得分:4)

除非您支持C ++ 11,否则需要将const char*传递给构造函数。你可以这样做:

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

请参阅此documentation for the relevant constructors

答案 1 :(得分:1)

您需要先将其转换为c字符串。

尝试myfile((filename).c_str())