我环顾四周,似乎无法找到这个问题的答案。我是 C++ 的新手,正在尝试为一个类(class)编写一个程序,该类(class)要求用户提供 4 名学生的名字和姓氏及其年龄。然后程序将显示输入的姓名和年龄,并显示平均年龄。
我遇到的问题是该程序允许输入名字和年龄,但随后会跳过剩余的三个姓名输入字段,只允许输入剩余的三个年龄。
如果这最终成为一个愚蠢的问题,我深表歉意,但我真的不知所措。任何帮助将不胜感激。
这是我到目前为止的代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string studentname1;
cout << "Please enter the first student's full name:" << endl;
getline(cin, studentname1);
int age1;
cout << "Please enter the first student's age:" << endl;
cin >> age1;
string studentname2;
cout << "Please enter the second student's full name:" << endl;
getline(cin, studentname2);
int age2;
cout << "Please enter the second student's age:" << endl;
cin >> age2;
string studentname3;
cout << "Please enter the third student's full name:" << endl;
getline(cin, studentname2);
int age3;
cout << "Please enter the third student's age:" << endl;
cin >> age3;
string studentname4;
cout << "Please enter the fourth student's full name:" << endl;
getline(cin, studentname2);
int age4;
cout << "Please enter the fourth student's age:" << endl;
cin >> age4;
cout << "Hello from our group." << endl;
cout << "NAME AGE" << endl;
cout << studentname1 << " " << age1 << endl;
cout << studentname2 << " " << age2 << endl;
cout << studentname3 << " " << age3 << endl;
cout << studentname4 << " " << age4 << endl;
cout << "The average of all our ages is: " << (age1 + age2 + age3 + age4) / 4.00 << endl;
return 0;
}
最佳答案
由于age
变量是int
,cin >> age1;
将在输入流中留下换行符。当您下次调用 getline()
时,您将获得该行的剩余部分 - 这是空的,依此类推。
此外,您的代码中存在复制粘贴错误。 getline(cint, studentname2);
为学生 2、3 和 4 运行。
您可以通过对所有输入使用 getline()
来解决问题:
string agestring;
getline(cin, agestring)
stringstream(agestring) >> age1;
或者在读完年龄后清除cin
:
cin >> age1;
cin.ignore();
关于c++ - 代码不允许用户在第一个字符串之后输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32432387/