Reputation: 15
Update: Thanks for the advice! Removing const from my function paramaters and replacing #include with #include , worked!
I'm new to C++ and I've looked up several posts, but can't seem to figure out why I am getting an "error: no matching function for call to 'getline'" from within my user defined function, when it is working fine from the main function.
I also don't understand why in some examples that I've seen online getline takes 2 paramaters (std::istream&, std::string&) and in others it takes 3 parameters (std::istream&, std::string&, char)
Have been racking my brain for a solution, would really appreciate if anyone can point out what I’m missing. sorry if this is a naive question!
condensed code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
char *myfunction (std::ifstream& infile, const std::string& strBuf){
//compile error "no matching function for call to 'getline'"
getline(infile, strBuf);
char *ptr= NULL;
return ptr;
}
int main() {
ifstream infile;
infile.open("myfile");
std::string strBuf;
getline(infile, strBuf);
// prints the first line of the file as expected
cout << strBuf << endl;
}
Upvotes: 1
Views: 481
Reputation: 206567
You can't read to a const
object.
Change the argument type from const std::string&
to just std::string&
.
char *myfunction (std::ifstream& infile, std::string& strBuf)
// ^^ No const
{
getline(infile, strBuf);
...
}
Also, as mentioned in a comment, don't forget to add
#include <string>
Upvotes: 4