std::getline 错误

Error with std::getline

所以这是代码:

#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

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

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

问题就在这里

void print_file(const ifstream& dat_in)

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

void print_file(ifstream& dat_in)

罪魁祸首是 const:

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

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

 void print_file(std::ifstream& dat_in)

让这个工作。


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

根据经验,传递并 return 所有流类型作为参考,既不是 const 也不是按值。请记住,const 指的是对象,而不是文件,即使文件是只读文件,对象也有很多可以改变的东西。