Input Issues with getline()
In a C program, you may encounter a peculiar behavior when using getline() to read user input. Specifically, if you ask for an integer, follow it with getline(cin, str), and then another integer, you'll notice that "Enter Account Number" appears before you get to input "str."
This occurs because getline() also captures the newline character entered after the first integer. To avoid this, you can instruct cin to skip whitespace before reading "str." Here's how:
cout << "Enter number:"; cin >> number; cout << "Enter name:"; cin.ignore(numeric_limits<streamsize>::max(), '\n'); getline(cin, str);
Here, cin.ignore() skips any whitespace, including the newline, before getline() reads the user's input.
Alternatively, you can use cin.get() to explicitly read and discard the newline character:
cout << "Enter number:"; cin >> number; cout << "Enter name:"; cin.get(); getline(cin, str);
This approach ensures that the newline is consumed, and getline() doesn't attempt to read it.
The above is the detailed content of Why Does `getline()` Skip Input After Reading an Integer in C ?. For more information, please follow other related articles on the PHP Chinese website!