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 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.

0

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);
1

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.

2

add this line work for me

#include <fstream>
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest