如何修复ifstream错误没有匹配的功能?

时间:2014-03-21 18:54:31

标签: c++

我不确定如何修复错误(如下)。有人能帮助我吗?

BTW:它在VS2012上运行很好,但是当我在linux终端上运行它会给我这个错误

错误:

  

Librarian.cpp:20:错误:没有用于调用的匹配函数   'std :: basic_ifstream> :: basic_ifstream(s   td :: string&,const std :: _ Ios_Openmode&)'

Librarian.cpp:

bool Librarian::addBooks(string file)
{
    ifstream infile(file);
    if (!infile) 
    {
        cerr << "File could not be opened." << endl;
        return false;
    }

    for (;;) {
        char s[MAX];
        infile.getline(s, MAX);
        if (infile.eof()) break;
        cout << s << endl;
    }
    return true;
}

1 个答案:

答案 0 :(得分:4)

根据std::basic_ifstream,构造函数在C ++ 11之前不会使用string&。在C ++ 11之前,只需要const char *。最简单的解决方案是:

 ifstream infile(file.c_str());

std::string::c_str()获取字符串的底层字符指针,以便您可以在构造函数中使用。或者您可以按照注释中的建议使用C ++ 11,但这取决于您的编译器版本(看起来您的编译器不支持它)。

相关问题