Reputation: 954
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
Upvotes: 1
Views: 1291
Reputation: 831
As a rule of thumb, pass and return all streams types as reference, neither const or by-value. Remember that const refers to the object, not the file and the object has many things that could change even if the file is a read-only file.
Upvotes: 0
Reputation: 1
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.
Upvotes: 3
Reputation: 1775
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)
Upvotes: 2
Reputation: 118425
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.
Upvotes: 1