代码跳过 getline 语句.我尝试了getline和cin都没有成功

Code skips the getline statement. I tried both getline and cin with no success

本文关键字:getline cin 成功 语句 代码      更新时间:2023-10-16

我阅读了一些关于如何修复它的答案,但我也在尝试理解它背后的概念(即为什么第一条getline工作正常)。

#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main(){
string ticker = "";
string date = "";
int pprice;
int sprice;
cout << "Enter the stock ticker =>" << endl;
getline(cin, ticker);
cout << "Enter the purchase price =>" << endl;
cin >> pprice;

它工作正常,直到它到达这里:

cout << "Enter the sell date =>" << endl; 
getline(cin, date);      
cout << "Enter the sell price =>" << endl;
cin >> sprice;
cout << ticker << endl;
return 0;
}
/*OUTPUT:
Enter the stock ticker =>
XYZ
Enter the purchase price =>
12.34
Enter the sell date =>
Enter the sell price =>
12.34
XYZ
*/

您可能没有在正确的位置使用cin.ignore()。应在std::cin之后和getline()之前使用。

例如:

int x;
string y;
cin >> x;
cin.ignore(INT_MAX);
getline(cin, y);

这个想法是删除 cin 在流中留下的回车符、换行符等,这些回车符会导致 getline() 立即获取并返回。