【问题标题】:No matching function - ifstream open()没有匹配的函数 - ifstream open()
【发布时间】:2013-05-09 07:10:48
【问题描述】:

这是有错误的代码部分:

std::vector<int> loadNumbersFromFile(std::string name)
{
    std::vector<int> numbers;

    std::ifstream file;
    file.open(name); // the error is here
    if(!file) {
        std::cout << "\nError\n\n";
        exit(EXIT_FAILURE);
    }

    int current;
    while(file >> current) {
        numbers.push_back(current);
        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return numbers;
}

好吧,我有点不知道发生了什么。整个事情在VS中正确编译。但是我需要用 dev cpp 编译它。

我在上面的代码中注释掉了抛出错误的行。错误是:

no matching function for call 'std::basic_ifstream<char>::open(std::string&)
no matching function for call 'std::basic_ofstream<char>::open(std::string&)

在代码的不同部分,我得到了像 numeric_limits is not a member of stdmax() has not been declared 这样的错误,尽管它们存在于 iostream 类中,并且在 VS 中一切正常。


为什么会出现这个错误?

【问题讨论】:

  • 你有适当的包含吗?得到你的包含 和包含 ?
  • 别生气,这通常是确切的原因:)
  • 我不是,我会问自己 ;d

标签: c++ string iostream


【解决方案1】:

改为:

file.open(name.c_str());

或者只使用构造函数,因为没有理由将构造和打开分开:

std::ifstream file(name.c_str());

在 c++11 中添加了对 std::string argument 的支持。

由于loadNumbersFromFile() 不会修改其参数,通过std::string const&amp; 传递以记录该事实并避免不必要的复制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多