【问题标题】:I cannot cin with getline [duplicate]我不能用 getline cin [重复]
【发布时间】:2017-10-22 19:30:46
【问题描述】:
int itrtn;
cout << "How many iterations? ";
cin >> itrtn;

double leftx, rightx,midx,midy;
cout << "Enter the endpoints of the interval containing the root: ";
cin >> leftx>>rightx;

cout<<"Enter the polynomial coefficients, ascending in degree: ";
string degree;
getline(cin,degree); // gets an entire line of input 
istringstream fake_keyboard(degree); // use fake keyboard like cin 
vector<double> coefficients;
double coeff;
while (fake_keyboard >> coeff) coefficients.push_back(coeff);

这是我的代码,但对于第三个问题,我无法使用 getline 进行 cin。编译器只是跳过这一步并将向量设置为默认值零

【问题讨论】:

  • fake_keyboard 的目的是什么?也许你需要真正的键盘。
  • 在您输入rightx 之后,您使用什么键将输入“传递”到您的程序? Enter 键?导致将换行符添加到输入缓冲区的那个?现在想一想std::getline 默认会寻找什么?

标签: c++ cin getline


【解决方案1】:

getline() 调用之前使用虚拟getchar()cin.get() 消耗额外的\n

cin >> leftx>>rightx;
cin.get(); //consume the '\n' of previous input.
cout<<"Enter the polynomial coefficients, ascending in degree: ";

【讨论】:

  • 这对 C++ 来说只是尴尬。如果我不会对此感到如此恼火,我会笑的。
猜你喜欢
  • 2017-03-07
  • 2016-02-05
  • 2012-01-10
  • 2021-08-26
  • 1970-01-01
相关资源
最近更新 更多