Home >Backend Development >C++ >Why Does `getline()` Return an Empty String After Number Input?

Why Does `getline()` Return an Empty String After Number Input?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 19:05:14471browse

Why Does `getline()` Return an Empty String After Number Input?

getline() Input Issues [Duplicate]

When using getline() to retrieve user input for a string variable (str), it's important to be aware of the newline character behavior. After retrieving a numerical value, a newline character remains in the input buffer. This can cause subsequent getline() calls to immediately return with an empty string.

In the code provided, the newline after the number input is not consumed,导致getline(cin, str) to immediately return with an empty string.

Solution:

To skip the newline character and ensure proper getline() behavior, use the ws (whitespace) manipulator:

cout << "Enter number:";
cin >> number;
cout << "Enter name:";
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, str);

The cin.ignore() statement reads and discards all remaining characters in the input buffer up to the next newline, effectively consuming the newline.

The above is the detailed content of Why Does `getline()` Return an Empty String After Number Input?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn