25

可能重复:
getline 不要求输入?

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

 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 the full name of student:
Age: 20

Father's Name:
Permanent Address: xyz

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

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

4

3 回答 3

87

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

使用getlinewith时的一个常见问题cingetline不会忽略前导空白字符。

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

如何解决?

打电话cin.ignore()前打电话getline()

或者

进行一个虚拟调用getline()以使用后面的换行符cin >>

于 2011-07-11T12:13:43.130 回答
4

问题是您正在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 );
于 2011-07-11T12:14:43.300 回答
1

在输入缓冲区cin >> age ;中仍然存在换行符\n(因为您按下回车键输入值),要解决此问题,您cin.ignore();在读取 ​​int 后添加一行。

于 2011-07-11T12:14:36.467 回答