以下是我的代码:
#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,程序将正常工作。
答案 0 :(得分:0)
;
getline (cin, name);
希望这会有所帮助
答案 1 :(得分:0)
cin >> age1;
未读取该数字后面的换行符。换行符保留在输入缓冲区中,然后过早地停止第二个getline
。
所以,只要你在同一行输入第一个年龄和第二个名字,你的程序就会already works。
一种解决方案是在数字后跳过空格:
cin >> age1 >> ws;
答案 2 :(得分:0)
首先: cin&gt;&gt;年龄;它需要数量和商店的年龄,但同样 它将换行符留在缓冲区本身的时间。所以当有下一个名字的提示时,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-&gt; shishir age1-&gt; 28 name2-&gt; ccr age-&gt; 22打印ccr younder!&lt; - 拼写错误:D
获取更多信息获取getline和get()阅读c ++ primer plus 列出4.3,4.4,4.5
快乐编码
答案 3 :(得分:0)
我建议使用cin.ignore(100,&#39; \ n&#39;)。它会忽略您在调用时指定的字符数(上例中为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');