问题
string add_text()
{
const int string_size(30);
string add_string;
cin.getline (add_string,string_size,'\n');
return add_string;
}
When I compile the program with the function above, I get an error. Note that I am using using namespace std;
earlier in the program. If it helps I am using Code Blocks and have also tried compiling the program using the Visual Studio 11 Professional Beta.
The Error:
C:\Users\Jonathan\Documents\Code_Blocks\test_12\main.cpp|32|error: no matching function for call to 'std::basic_istream<char, std::char_traits<char> ::getline(std::string&, const int&, char)'|
Any help with this issue will be greatly appreciated, thanks in advance!
回答1:
You're calling std::istream::getline(char *, streamsize) - you can see it requires a char *
instead of the std::string
you're passing.
Use std::getline(std::istream&, std::string&, char) instead, like so:
getline(cin, add_string, '\n');
回答2:
istream::getline
doesn't take a std::string
as parameter, but a char*
. You can fix it by calling the function correctly.
So, provided you know the max size of the line:
char buff[256]; //or whatever length
cin.getline (buff,string_size,'\n');
string add_string(buff);
回答3:
Don't use member .getline()
s, but global std::getline().
Member .getline()
s can only use char *
as buffer, while std::getline()
can use std::string
.
回答4:
cin.getline
is a member function. As such, it is not overloaded to account for every possible type in existence. So, developers overload the global version (i.e., std::getline
).
来源:https://stackoverflow.com/questions/10625701/how-do-i-fix-a-no-instance-of-overloaded-function-error-with-cin-getline