cin >>不能使用getline()

Wiz*_*ard 0 c++ cin getline

#include <iostream>
#include <string>
using namespace std;

int main () {
  string str;
  int age;
  cout << "Please enter age: ";
  cin>>age;
  cout << "Please enter full name: ";
  getline (cin,str);
  cout << "Thank you, " << str << ".\n";
}
Run Code Online (Sandbox Code Playgroud)

当我使用uperator >>输入整数时,为什么函数getline()不起作用?int输入有什么更好的用途?

Fre*_*son 5

之后流中仍然有换行符cin>>age;,它为您提供了一个名称的空字符串.

您可以通过getline()在获得年龄并丢弃结果后添加另一个调用来解决它.另一种选择是调用cin.ignore(BIG_NUMBER, '\n');,其中BIG_NUMBERMAX_INT或其他东西.

  • `std :: cin.ignore(std :: numeric_limits <std :: streamsize> :: max(),'\n');` (2认同)