So this is the code:
#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;
}
}
And I get an error that no instance of overloaded function std::getline
matches the argument list.
I did this line of code a thousand of times, what is the problem now ...
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
答案 0 :(得分:2)
the problem is here
void print_file(const ifstream& dat_in)
getline
necessarily changes the stream
that is passed-in. So change the above to (remove const
)
void print_file(ifstream& dat_in)
答案 1 :(得分:2)
The culprit is the const
:
void print_file(const std::ifstream& dat_in)
// ^^^^^
Of course the std::ifstream
's state is changed when reading data from it, thus it cannot be const
in that context. You should simply change your function signature to
void print_file(std::ifstream& dat_in)
to get this working.
BTW the function name print_file
is pretty confusing for a function that actually reads from a file.
答案 2 :(得分:1)
Your code is passing a reference to a const ifstream
parameter as the first parameter to std::getline()
. Since std::getline()
modifies its input stream parameter, it cannot have a const
reference as the first parameter.
The error message from the compiler included a list of all the parameters, and it should've indicated that the first parameter is a const
reference.
答案 3 :(得分:0)
根据经验,传递并返回所有流类型作为引用,既不是const也不是by-value。请记住,const指的是对象,而不是文件,即使文件是只读文件,对象也有许多可能改变的东西。