代码不允许用户在第一个字符串后输入字符串

时间:2015-09-07 06:30:48

标签: c++

我环顾四周,似乎无法找到答案。我是C ++的新手,我正在尝试为一个类编写程序,该程序要求用户提供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;

}

1 个答案:

答案 0 :(得分:1)

由于age变量为intcin >> age1;将在换行流中保留换行符。接下来你打电话给getline(),你将获得该行的剩余部分 - 这是空的,依此类推。

此外,您的代码中存在复制粘贴错误。 {2,3}为2名学生和3名学生开设。

您可以使用getline(cint, studentname2);对所有输入解决问题:

getline()

或在您阅读完年龄后清除string agestring; getline(cin, agestring) stringstream(agestring) >> age1;

cin