Home > Backend Development > C++ > Why Does `getline()` Skip Input After Reading an Integer?

Why Does `getline()` Skip Input After Reading an Integer?

Mary-Kate Olsen
Release: 2024-12-16 21:06:11
Original
224 people have browsed it

Why Does `getline()` Skip Input After Reading an Integer?

getline() Issues: Skipping the Newline

When using getline(cin, str) to retrieve user input after reading an integer using cin >> number, you may encounter an unexpected behavior where the prompt for the name skips the input for str. This occurs because getline(cin, str) reads and discards the newline character left by the previous integer input.

To address this issue, you can employ std::ws before getline(cin, str) to skip whitespace, including newlines, before reading the string. This ensures that getline(cin, str) correctly reads the user input without skipping the name prompt:

int number;
string str;
int accountNumber;

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

By using cin.ignore, you efficiently bypass any remaining whitespace or newlines, allowing getline(cin, str) to capture the user's name input as intended.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template