Unexpected Behavior with getline() in C++ Input Loop
In an attempt to obtain user input from the console, a developer encountered a puzzling issue with the getline() function. Contrary to expectations, the program failed to wait for input after the first call to getline(), proceeding immediately to the subsequent call.
The provided code snippet illustrates the problematic section:
getline(cin, inputString); getline(cin, inputString);
This behavior arises from the combination of getline() and the input operator (>>) within the same input loop. While >> skips leading whitespace, it fails to consume trailing newline characters. When followed by a getline() call, the newline remains in the input buffer and is interpreted as part of the next input.
Solution:
To resolve this issue, it is necessary to consistently use either getline() or >> throughout the input loop. If all inputs are numerical or can be efficiently parsed, >> is a suitable choice. However, if strings or a mix of data types are involved, getline() should be employed and the numeric values extracted from the input strings manually.
Code Refactor:
Using getline() for all inputs:
getline(cin, inputString); getline(cin, inputString); getline(cin, inputUInt); getline(cin, inputUInt); getline(cin, inputDouble);
Alternatively, using >> for all numeric inputs:
cin >> inputString; cin >> inputString; cin >> inputUInt; cin >> inputUInt; cin >> inputDouble;
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!