No Matching Function to Call for "Getline"
I'm New to C++ Programming. in a Tutorial, the Author Mentioned "Cin" Will Break If It Reads a Space in a String. If You Want the Program to Read in an Entire...
I'm new to c++ programming. In a tutorial, the author mentioned "cin" will break if it reads a space in a string. If you want the program to read in an entire line of string with spaces, you should use the function "getline".
However, I couldn't make it work.
Here are my codes:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string my_name;
cout << "Please enter your name: ";
getline(cin, my_name, "\n");
cout << "My name is " << my_name << " .";
}
The IDE I am using is Xcode. The error message is "No matching function to call to 'getline'".
I have searched for similar issues but it seems to me none of the solutions apply to my problem. Maybe I am missing some knowledge? Thank you.
4 Answers
The complete error would tell you why your third parameter is of the wrong type.
It should be a character type, not a null-terminated string of characters.
getline(cin, my_name, '\n');
Edit: And, '\n' specifically is the assumed delimiter in another form of getline:
getline(cin, my_name);
What your teacher said is not true. cin will not "break". It's just that formatted extraction into an std::string is designed to read word by word. That's intentional. It's not broken.
As for your error, your call to std::getline is broken because the delimiter argument has the wrong type. '\n' is a char literal; "\n" is a char array literal, not at all what you wanted.
add this line work for me
#include <fstream>
If you change it to a char array you can use:
cin.getline(my_name, val_max);
Just make sure your buffer (val_max) is large enough