'getline() error in c++ despite defined library?

i have Array, i want to ask user enter Full name. Getline shows error but i don't know why, i have defined library:

#include <iostream>
#include <string>
int main()
{
    using namespace std;
    const int ArSize = 20;
    char name[ArSize];
    char dessert[ArSize];
    cout << "Enter your name:\n";

    getline(cin, name) ;

    cout << "Enter your favorite dessert:\n";
    cin >> dessert;
    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
    return 0;
}

enter image description here

c++


Solution 1:[1]

The global function getline expects a std::string& as the second parameter, not a null terminated string (or array of char). See http://en.cppreference.com/w/cpp/string/basic_string/getline.

The member function std::istream::getline can work with an array but it needs a second parameter. See http://en.cppreference.com/w/cpp/io/basic_istream/getline.

You can use either:

std::string name;
getline(cin, name) ;

or

char name[ArSize];
cin.getline(name, sizeof(name));

Solution 2:[2]

the main reason is: make difference between cin.getline(char*, int) and getline(cin, string).

cin.getline() Extracts characters from the stream as unformatted input and stores them into s as a c-string. getline is a member function of istream. your code will look like:

cin.getline(name, ArSize);

the other version of getline is being a function that takes a string it is not member of any calss this why we don't use member access operator to call it.

string name;
getline(cin, name);

Solution 3:[3]

Try cin.getline(name,ArSize);.

Solution 4:[4]

paste this at the top of your code !

#include <cstring>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 R Sahu
Solution 2
Solution 3 Chief
Solution 4 Youssef Mohammed