【问题标题】:cin>> not work with getline()cin>> 不适用于 getline()
【发布时间】:2012-01-10 01:19:02
【问题描述】:
#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";
}

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

【问题讨论】:

  • 定义“不工作”。发生了什么你不喜欢的事情?

标签: c++ getline cin


【解决方案1】:

cin&gt;&gt;age; 之后的流中仍有一个换行符,它为您提供了一个空字符串作为名称。

您可以通过在获取年龄并丢弃结果后添加另一个 getline() 调用来解决它。另一种选择是调用cin.ignore(BIG_NUMBER, '\n');,其中BIG_NUMBER 是MAX_INT 之类的。

【讨论】:

  • 调用getline() 两次可以解决问题,但更有效的解决方案是在真正的getline() 之前调用cin.ignore()
  • @ildjarn:好主意。我会将其添加到我的答案中。
  • 您的ignore 调用需要一个分隔符。
  • @BillyONeal:哦,确实如此。它默认为 EOF,而不是换行符!这就是为什么我首先选择getline()。 8v)
  • std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n');
【解决方案2】:

getline() 不能与 int 或任何数字一起使用。它是这样定义的:

istream& getline (char* s, streamsize n );

istream& getline (char* s, streamsize n, char delim );

所以,它接受字符串和char*'s;不是数字。

【讨论】:

  • getline() 用于名称,而不是整数。仔细看看这个问题。
  • 和数字也是字符:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多