Problem of std::getline() Skipping Input After a Formatted Extraction
The std::getline() function skips input when used after a formatted extraction operation. This issue arises due to the behavior of formatted extraction operations that are used to extract data in a predefined format from an input stream, such as std::cin >>, which leaves the newline character (‘\n’) in the input buffer. When std::getline() is called after that, it reads until it encounters a newline character, which is still in the buffer from the previous input. As a result, std::getline() immediately stops reading and returns an empty string, giving the impression that it has skipped input.
Example 1: Showing the Case where std::getline() Skips the Input
// C++ Program where getline() skips input after a formatted
// extraction
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
string str;
cout << "Enter a number: ";
// read a number
cin >> num;
cout << "Enter a string: ";
// try to read string
getline(cin, str);
cout << endl;
cout << "Number: " << num << endl;
cout << "String: " << str << endl;
return 0;
}
Output
Enter a number: 5 Enter a string: Number: 5 String:
Explanation: In the above code, we entered a number and then a string, we noticed that the program doesn’t pause for the string input and str remains empty only.
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.
Contact Us