C++ std::getline错误
这就是代码:C++ std::getline错误,c++,getline,C++,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");
#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;
}
}
代码正在将对
const ifstream
参数的引用作为std::getline()
的第一个参数传递。由于std::getline()
修改其输入流参数,因此它不能将const
引用作为第一个参数
来自编译器的错误消息包括一个所有参数的列表,它应该指示第一个参数是
const
引用。您的代码正在将对const ifstream
参数的引用作为第一个参数传递给std::getline()
。由于std::getline()
修改其输入流参数,因此它不能将const
引用作为第一个参数
来自编译器的错误消息包括一个所有参数的列表,它应该表明第一个参数是一个const
引用。问题就在这里
void print_file(const ifstream& dat_in)
getline
必须更改传入的流。因此,将上述内容更改为(删除const
)
问题就在这里
void print_file(const ifstream& dat_in)
getline
必须更改传入的流。因此,将上述内容更改为(删除const
)
罪魁祸首是常量
:
void print_file(const std::ifstream& dat_in)
// ^^^^^
当然,std::ifstream
的状态在从中读取数据时会发生更改,因此在该上下文中不能是const
。您只需将函数签名更改为
void print_file(std::ifstream& dat_in)
让它工作起来
顺便说一句,函数名print\u file
对于实际从文件读取的函数来说是相当混乱的。罪魁祸首是const
:
void print_file(const std::ifstream& dat_in)
// ^^^^^
当然,std::ifstream
的状态在从中读取数据时会发生更改,因此在该上下文中不能是const
。您只需将函数签名更改为
void print_file(std::ifstream& dat_in)
让它工作起来
顺便说一句,对于实际从文件读取的函数来说,函数名“print_file”非常容易混淆。根据经验,传递并返回所有流类型作为引用,而不是常量或按值。请记住,const指的是对象,而不是文件,并且即使文件是只读文件,对象也有许多可能更改的内容。根据经验,传递和返回所有流类型作为引用,而不是const或by value。请记住,const指的是对象,而不是文件,并且即使文件是只读文件,对象也有许多可能更改的内容