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

标签 c++

我环顾四周,似乎无法找到这个问题的答案。我是 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 变量是intcin >> 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/

相关文章:

c++ - 从网络服务器传输套接字文件

c++ 定义静态类函数

c++ - 2 条语句用正则 new 表达式创建对象,有什么区别吗?

c++ - 捕获多个异常

c++ - 内存编辑: Can't get right address (3 offsets)

c# - 你如何在 C++ 中调用 C# 方法?

python - C++ 17 与 Python 2.7 的兼容性

c++ - 返回指向列表中对象的指针

c++ - 在 C++ 中的线程之间传递队列

c++ - 如何在 Qt 5 中写入和读取 QResource 文件?