getline无法正常工作?可能是什么原因?

时间:2011-07-11 12:07:57

标签: c++ visual-c++ getline

  

可能重复:
  getline not asking for input?

我的程序中发生了一些独特的事情。 以下是一些命令:

 cout << "Enter the full name of student: ";  // cin name
 getline( cin , fullName );

 cout << "\nAge: ";  // cin age
 int age;
 cin >> age ;

cout << "\nFather's Name: ";  // cin father name
getline( cin , fatherName );

cout << "\nPermanent Address: ";  // cin permanent address
getline( cin , permanentAddress );

当我尝试将此代码段与整个代码一起运行时。输出程序的工作方式如下:

enter image description here

输出:

Enter the full name of student:
Age: 20

Father's Name:
Permanent Address: xyz

如果你注意到,程序没有问我全名,而是直接问我年龄。然后它也会跳过父亲的名字并询问永久地址。 可能是什么原因?

我很难发布整个代码,因为它太大了。

3 个答案:

答案 0 :(得分:53)

由于您尚未发布任何代码。我要猜一猜。

getline使用cin getline时遇到的常见问题是cin >>不会忽略前导空白字符。

如果在getline()之后使用了getline,则cin.ignore()会将此换行符视为前导空格,并且它会再停止阅读。

如何解决?

在致电getline()

之前致电getline()

进行虚拟调用cin >>以使用{{1}}

中的尾随换行符

答案 1 :(得分:3)

问题是您要将getlinecin >>输入混合。

执行cin >> age;时,它会从输入流中获取年龄,但会在流上留下空白。具体来说,它将在输入流上留下一个换行符,然后在下一个getline调用时将其读取为空行。

解决方案是仅使用getline获取输入,然后解析该行以获取所需信息。

或者为了修复您的代码,您可以执行以下操作,例如: (您仍然需要自己添加错误检查代码):

cout << "Enter the full name of student: ";  // cin name
getline( cin , fullName );

cout << "\nAge: ";  // cin age
int age;
{
    std::string line;
    getline(cin, line);
    std::istringstream ss(line);
    ss >> age;
}

cout << "\nFather's Name: ";  // cin father name
getline( cin , fatherName );

cout << "\nPermanent Address: ";  // cin permanent address
getline( cin , permanentAddress );

答案 2 :(得分:1)

在行cin >> age ;之后仍然有换行符\n(因为您按Enter键输入值),为了解决此问题,您需要添加一行cin.ignore();读完int。