c++ - 如何修复没有匹配函数 ifstream 错误?

标签 c++

<分区>

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

顺便说一句:它在 VS2012 上运行良好,但是当我在 linux 终端上运行时它给了我这个错误

错误:

Librarian.cpp:20: error: no matching function for call to ‘std::basic_ifstream >::basic_ifstream(s td::string&, const std::_Ios_Openmode&)’

图书管理员.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;
}

最佳答案

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

 ifstream infile(file.c_str());

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

关于c++ - 如何修复没有匹配函数 ifstream 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22567256/

相关文章:

c++ - 我的输出中有一个额外的 0,这是为什么

c++ - QTimer::singleShot 仅在间隔为 0 时调用 lambda

c++ - 复古游戏: scaling all sprites or rather the entire canvas?

c++ - 用户定义的文字作为可变参数模板

c++ - 当数组内容改变时更新指向数组元素的指针

c++ std::vector 迭代器构造函数 first == last

c++ - STL find_if 和不区分大小写的字符串比较

c++ - MFC:通过发布消息触发菜单操作需要什么?

c++ - 提振 spirit 如何从父节点访问子节点(叶子)

c++ - 验证用户输入为坐标(A1…)