【问题标题】:Error with std::getlinestd::getline 错误
【发布时间】:2016-07-11 22:56:42
【问题描述】:

代码如下:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

void print_file(const ifstream& dat_in)
{
    if(!dat_in.is_open())
        throw ios_base::failure("file not open");

    string buffer;
    while(getline(dat_in, buffer));  //error here
}

int main()
{
    ifstream dat_in("name_of_the_file.txt");

    try{
        print_file(dat_in);
    }
    catch(ios_base::failure exc){
        cout << exc.what() << endl;
    }
}

我收到一个错误,即没有重载函数 std::getline 的实例与参数列表匹配。 这行代码我做了一千遍,现在是什么问题...

3 IntelliSense: no instance of overloaded function "getline" matches the argument list
        argument types are: (const std::ifstream, std::string)  
Error 1   error C2665: 'std::getline' : none of the 2 overloads could convert all the argument types

【问题讨论】:

    标签: c++ getline


    【解决方案1】:

    罪魁祸首是const

     void print_file(const std::ifstream& dat_in)
                  // ^^^^^
    

    当然,std::ifstream 的状态在从它读取数据时会发生变化,因此在这种情况下它不能是 const。您只需将函数签名更改为

     void print_file(std::ifstream& dat_in)
    

    让这个工作。


    顺便说一句,函数名称 print_file 对于实际从文件中读取的函数来说非常令人困惑。

    【讨论】:

      【解决方案2】:

      问题来了

      void print_file(const ifstream& dat_in)
      

      getline 必然会更改传入的stream。所以把上面的改成(去掉const

      void print_file(ifstream& dat_in)
      

      【讨论】:

        【解决方案3】:

        您的代码将对const ifstream 参数的引用作为第一个参数传递给std::getline()。由于std::getline() 修改了它的输入流参数,所以它不能将const 引用作为第一个参数。

        来自编译器的错误消息包括所有参数的列表,它应该表明第一个参数是const 引用。

        【讨论】:

          【解决方案4】:

          根据经验,传递和返回所有流类型作为引用,既不是 const 也不是按值。请记住,const 指的是对象,而不是文件,即使文件是只读文件,对象也有很多可能会改变的东西。

          【讨论】:

            猜你喜欢
            • 2013-12-13
            • 2014-10-18
            • 1970-01-01
            • 1970-01-01
            • 2011-10-12
            • 2010-09-20
            • 1970-01-01
            • 2020-03-14
            • 2011-01-21
            相关资源
            最近更新 更多