gpt4 book ai didi

c++ - std::getline 错误

转载 作者:行者123 更新时间:2023-11-30 01:10:16 25 4
gpt4 key购买 nike

所以这是代码:

#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:

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

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

 void print_file(std::ifstream& dat_in)

让它工作。


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

关于c++ - std::getline 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38317471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com