0

In many answers and questions such as this one, it is recommended to use cin.getline from <string> and not getline(cin, variable):

#include <iostream>
#include <string>

using namespace std;

int main() {
    string name;
    cin.getline(name);
}

But in my case I have build issue:

g++ foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:8:21: error: no matching function for call to 
   ‘std::basic_istream<char>::getline(std::string&)’
    8 |     cin.getline(name);
      |                     ^
nowox
  • 25,978
  • 39
  • 143
  • 293

1 Answers1

1

From the error told by the compiler, it is evident that there is no such function overload that accepts a type reference to std::string (for cin.getline()). Rather, it accepts parameters like:

const int MAX = 100;

char input[MAX];
cin.getline(input, MAX);
// Or better
// cin.getline(input, sizeof input);
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • So there is no OOP method on `cin` to read a string with spaces, one needs `std::getline` – nowox Sep 19 '20 at 15:21
  • @nowox the `cin.getline()` also accepts whitespaces. See [live](https://onlinegdb.com/HyG_MsQrw). But `std::getline()` is more convenient to use. – Rohan Bari Sep 19 '20 at 15:23