"getline" 提示被跳过,未按预期工作

"getline" prompt gets skipped, not working as intended

这是我的代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int age1;
    int age2;
    string name1;
    string name2;

cout << "Please enter the name for one people: " << "\n";
getline (cin, name1);
cout << "Please enter the age for this people: " << "\n";
cin >> age1;

cout << "Please enter the name for another people: " << "\n";
getline (cin, name2);
cout << "Please enter the age for this people too: " << "\n";
cin >> age2;

if ( (age1 <= 100 || age2 <= 100) && (age1 < age2) )
{
    cout << name1 << " is younger!" << "\n";
}
else if ( (age1 <= 100 || age2 <= 100) && (age1 > age2) )
{
    cout << name2 << " is younder!" << "\n";
}
else if ( (age1 <= 100 || age2 <= 100) && (age1 = age2) )
{
    cout << name1 << " and " << name2 << " are of the same age!" << "\n";
}
else
{
    cout << "You've got some really old people that are well older than 100!";
}
}

第一个 getline 和 cin 工作正常。我能够被提示输入。 但是第二个getline和cin一下子提示,所以我只能输入cin。 (跳过第二个getline!)

如果我使用四个cins,程序就可以正常运行。

getline (cin, name);

之后你需要一个 ;

希望这对您有所帮助

cin >> age1; 不读取数字后面的换行符。换行符保留在输入缓冲区中,然后过早地停止第二个 getline.

所以,你的程序already works只要在同一行输入第一个年龄和第二个名字即可。

一个解决方案是跳过数字后的空格:

cin >> age1 >> ws;

Live demo.

首先: cin>>年龄;它将数字和存储带入年龄但同时 时间它将换行符留在缓冲区本身中。因此,当提示输入下一个名称时,cin 会发现缓冲区中剩余的换行符并将其作为输入。这就是它逃避 name2 提示的原因。

    cout << "Please enter the name for one people: " << "\n";       
    cin>>name1;
    cout << "Please enter the age for this people: " << "\n";
    cin >> age1;<<--**this left the new line character in input buffer**
    cin.get();<<-- **get that newline charachter out of there first**
    cout << "Please enter the name for another people: " << "\n";
    getline (cin, name2);
    cout << "Please enter the age for this people too: " << "\n";
    cin >> age2;

现在 我给name1-> shishir age1->28 name2->ccr age-> 22 它打印 ccr is younder!<-- 拼写也有误 :D

有关 getline 和 get() 的更多信息 阅读 c++ 入门书以及 清单 4.3、4.4、4.5

编码愉快

我建议使用 cin.ignore(100,'\n')。它会忽略您在调用它时指定的字符数(上例中为 100 个),直到您指定为断点的字符。例如:

cout << "Please enter the name for one people: " << "\n";
getline (cin, name1);
cout << "Please enter the age for this people: " << "\n";
cin >> age1;
cin.ignore(100, '\n');
cout << "Please enter the name for another people: " << "\n";
getline (cin, name2);
cout << "Please enter the age for this people too: " << "\n";
cin >> age2;
cin.ignore(100, '\n');