-2

I have a function which should very simply read in a line of text, but for whatever reason, it only reads a space. I tried changing the readline to a cin >> line, and that worked. But the readline(cin, string) does not.

void AddRestaurant() {
    string restToAdd;
    cout << "What is the name of the restaurant you want to add?" << endl;
    getline(cin, restToAdd);
    restuarants.push_back(restToAdd);
    cout << restToAdd + " has been added" << endl << endl;
}

Anybody see my error?

Taylor Barton
  • 45
  • 1
  • 10
  • 1
    You don't check if getline (not readline) actually read anything - you should check the return value of every function that performs a read, as they can all fail for a variety of reasons. –  Nov 01 '17 at 00:04
  • 2
    Yes, your error is very obvious: your question fails to meet all the requirements for a [mcve], as explained in stackoverflow.com's [help]. That's your problem. – Sam Varshavchik Nov 01 '17 at 00:05
  • Are you pushing back to a vector? if not that could be an error – Pouya Nov 01 '17 at 00:09
  • 1
    Most likely, there is previous input left over in `cin` from earlier code, which `getline()` is then reading but `operator>>` is skipping. `operator>>` ignores leading whitespace including line breaks (unless `std::noskipws` is used), whereas `getline()` reads everything up to a specified delimiter (line break by default) without skipping. – Remy Lebeau Nov 01 '17 at 03:04
  • See [Why does std::getline skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Bo Persson Nov 01 '17 at 03:19

1 Answers1

2

That is not an error. It seems that you have done a cin>> operation earlier. cin>> takes just the string from the stream and leaves behind the \n, which the getline(), probably picks up, and as you know its default delimiter is \n, so it just skips the input.

Solution---> using cin.ignore() before every getline () operation to clear the input stream of any stray \n.

Your call can be:

std::cin.ignore ();
std::getline (cin, restToAdd);

Instead of:

std::getline (cin,restToAdd);
Pang
  • 8,605
  • 144
  • 77
  • 113
Vedant
  • 125
  • 13
  • It is often better to put the `ignore` after the `>>` that left the end of line in the stream. 2 reasons: The fix is closer to the source of the problem so the two may be more easily visually tied together when reading through the code and if someone calls `AddRestaurant` and there isn't an end of line in the stream, the first byte of the restaurant's name just got discarded. – user4581301 Nov 02 '17 at 19:03