首页 > 解决方案 > 我在 ifstream input_file(filename); 行中收到错误“没有要调用的匹配函数”;

问题描述

int main(int argc, const char * argv[]) {

    cout << "Give the name of the input file : ";
    string filename;
    cin >> filename;

    cout << "Reading from " << filename << "..." << endl;

    ifstream input_file(filename);
    if( !input_file ) {
        // stuff...
    }
}

标签: c++

解决方案


假设您有#include <fstream>并且using namespace std;在您的代码中,然后更改此:

ifstream input_file(filename);

对此:

ifstream input_file(filename.c_str());

在您的编译器版本的 C++ 中,std::ifstream构造函数仅将 aconst char*作为输入,而不是 a std::string。需要 C++11 才能按std::string原样传递。如果你的编译器支持 C++11,可能你没有启用它。检查编译器的文档。


推荐阅读