In the C++ standard library, std::getline() is used to read a line of text from an input stream, commonly used with std::istream types such as std::cin. When using std::getline() to read data, a common issue may arise: directly calling std::getline() after formatted input (e.g., using the >> operator) causes it to skip input. This is typically because formatted input operations leave the newline character in the input buffer.
Explanation
When using the >> operator to read data from std::cin, such as reading an integer or string, the input operation stops at the first whitespace character (e.g., space or newline). This typically means the newline character , generated when you press Enter, remains in the input buffer. When you subsequently call std::getline(), it reads from the current buffer position until it encounters the next newline character. Since the first character in the input buffer is , std::getline() interprets this as an empty line and stops reading immediately.
Example
cpp#include <iostream> #include <string> int main() { int number; std::string line; std::cout << "Enter a number: " << std::endl; std::cin >> number; // Assume input of 123 and pressing Enter std::cout << "Enter a sentence: " << std::endl; std::getline(std::cin, line); // This reads an empty string std::cout << "Number is: " << number << std::endl; std::cout << "Sentence is: " << line << std::endl; // Output will be empty return 0; }
Solution
To resolve this issue, use std::cin.ignore() to clear any remaining characters in the input buffer after formatted input, particularly the newline character. std::cin.ignore() can be used to ignore characters in the buffer until a specified terminator character is encountered, typically a newline character.
Modified example:
cpp#include <iostream> #include <string> int main() { int number; std::string line; std::cout << "Enter a number: " << std::endl; std::cin >> number; // Assume input of 123 and pressing Enter std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Ignore until newline std::cout << "Enter a sentence: " << std::endl; std::getline(std::cin, line); std::cout << "Number is: " << number << std::endl; std::cout << "Sentence is: " << line << std::endl; return 0; }