Why does std::getline() skip input after a formatted extraction?

C++Server Side ProgrammingProgramming

The std::getline() skips input after some formatted extraction. We can simply check this error from the following code −

Example Code

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

int main(){
   string name;
   string city;

   if (cin >> name && getline(cin, city)){
      cout << "Your name " << name << " and city " << city;
   }
}

Output

Amal
Your name Amal and city

We can see that the program does not take the second input. Sometime it may take the second input but in the output it will show only the first input. Now the question is why it is behaving like this?

The main reason of this problem is that when we are writing the first string, then we are pressing the Enter or Return button. When Enter or Return is pressed, it inserts ‘\n’ character after the current line. This character is generating the problem. It is ignoring the next part of the string.

If the name is “Amal”, then internally it is getting “Amal\n”. To overcome this problem one option is to call std::cin.ignore() after the first extraction. Then it will discard next available character, so it will work fine.

raja
Published on 02-Apr-2019 08:12:01
Advertisements