Preventing std::getline() from Skipping Input
To resolve the above issue we can use the std::cin.ignore() function after the formatted extraction operation that extracts and discards characters from the input buffer until it encounters a newline character or reaches a specified limit.
C++ Program to Use getline() Without Skipping Input after a Formatted Extraction
The below example demonstrates how we can take input using gettline() without skipping input after a formatted extraction.
// C++ Program to demonstrates how we can take input using
// gettline() without skipping input after a formatted
// extraction.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int number;
string str;
// Read an integer
cout << "Enter a number: ";
cin >> number;
// Ignore the newline character left in the buffer
cin.ignore();
// Read a line of text
cout << "Enter a string: ";
getline(cin, str);
// print the number and string
cout << "Number: " << number << endl;
cout << "String: " << str << endl;
return 0;
}
Output
Enter a number: 5 Enter a string: Hello Number: 5 String: Hello
Explanation: In the above code, std::cin.ignore() discards all characters up to the end including the next newline character. Now, the program correctly pauses for the string input after the number input.
Why Does std::getline() Skip Input After a Formatted Extraction?
In C++, the std::getline() function is a common method for reading a line of text from an input stream. However, when used after a formatted extraction operation, it may sometimes skip input. In this article, we will learn why does std::getline() skips input after a formatted extraction and how to prevent it.