-3

I keep getting this error (it's a really long one but I think the most important part is this):

main.cpp:9:30: note:   mismatched types 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>' and 'const char [2]'

While compiling this bit of code:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string x = getline(cin, " ");
    return 0;
}

The lines in the error won't match with the ones in the code I brought up here because I don't know how to make a new line whilst writing code in the Stack Overflow editor; I'm new here ;) Anyways, the error points to the line with the declaration of string x.

Basically what I want this code to do is to get a line from the user until he/she hits space. Maybe I'm doing something wrong from the beginning, so I'm open for suggestions of fixing this problem. (I'm not very experienced in C++, it's just that my teacher required to complete a task using this language.) Thanks,

Anthony

Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
aachh
  • 93
  • 2
  • 5
  • 2
    why would you use `" "` in the second argument of `std::getline()`? What do you thnk it does? – Fureeish Dec 23 '18 at 19:57
  • Did you read the reference: https://en.cppreference.com/w/cpp/string/basic_string/getline ? it seems you don't understand what parameters to pass (or what the return value is) – UnholySheep Dec 23 '18 at 20:01
  • @Fureeish never mind, I've just found the source of the problem. I just remembered the getline formula wrong; I can't assign the returned value of getline() to a variable, I would have to do getline(cin, x, ' '), having declared string x before to make it work. – aachh Dec 23 '18 at 20:04
  • Thanks you all wrote back so fast, I managed to fix the problem. – aachh Dec 23 '18 at 20:06

1 Answers1

1

The second parameter of std::getline() is a reference to a std::string variable that accepts the read data. The string is not outputted in the function's return value.

Also, std::getline() does not accept a string for the delimiter. It takes only a single character.

Try this instead:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string x;
    getline(cin, x, ' ');
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770