为什么程序在调用函数时跳过接受输入

Why does the program skip taking input when function is called?

本文关键字:输入 程序 调用 函数 为什么      更新时间:2023-10-16

我正在编写一个简单的C++程序,该程序获取学生信息及其在不同科目中的分数。

#ifndef STUDENT_H_
#define STUDENT_H_
#include<string>

class Student {
private:
    std::string name;
    std::string dept;
    unsigned char age;
    std::string usn;
public:
    Student();
    void getinfo();
    void display();
    virtual ~Student();
};

 class Score:public Student {
 private:
     int math;
     int sci;
     int chem;
     int english;
     int SS;
 public:
     void marks();
     void dispscore();
     Score();
};
 #endif /* STUDENT_H_ */

以上是头文件。

#include "Student.h"
#include <iostream>
 using namespace std;
 Student::Student()
{
 age = 0x00;
}
Student::~Student()
{
}
 Score::Score()
 {
     math = 0x00;
     sci = 0x00;
     chem = 0x00;
     SS = 0x00;
     english = 0x00;
 }
 void Student::getinfo()
 {
     cout<<"Enter the Students Name: "<<endl;
     getline(cin,name);
     cout<<"Enter Department--> "<<endl;
     getline(cin,dept);
     cout<<"Enter USN--> "<<endl;
     getline(cin,usn);
     cout<<"Enter Age--> "<<endl;
     cin>>age;
 }
 void Student::display()
 {
     cout<<name<<endl;
     cout<<dept<<endl;
     cout<<usn<<endl;
     cout<<age<<endl;
 }
 void Score::marks()
  {
     cout<<"Enter Math Score: "<<endl;
     cin>>math;
     cout<<"Enter Science Score: "<<endl;
     cin>>sci;
     cout<<"Enter Chemistry Score:  "<<endl;
     cin>>chem;
     cout<<"Enter English Score: "<<endl;
     cin>>english;
     cout<<"Enter the Social Studies Score: "<<endl;
     cin>>SS;
 }
  void Score::dispscore()
 {
     cout<< math << endl;
     cout<<sci<<endl;
     cout<<chem<<endl;
     cout<<english<<endl;
     cout<<SS<<endl;
 }
 int main()
 {
     Score s;
     s.getinfo();
     s.marks();
     s.display();
     s.dispscore();

 }

以上是 cpp 文件。编译后,我得到如下所示的输出,并面临以下问题,它们是:1.跳过数学的输入分数,直接从科学的输入分数开始,2. 输入的年龄是 23 岁,但是在控制台中,它不会将其显示为"23",而是在一行显示为 2,下一行显示为 3,如输出所示 ->发生这种情况是因为我按回车

键吗?
Enter the Students Name: 
Smith Diaz
Enter Department--> 
ECE
Enter USN--> 
4So08ec112
Enter Age--> 
23
Enter Math Score: 
Enter Science Score: 
77
Enter Chemistry Score:  
66
Enter English Score: 
89
Enter the Social Studies Score: 
57
Smith Diaz
ECE
4So08ec112
2
3
77
66
89
57

age的类型为 unsigned char ,因此cin只读一个字符并将其存储在那里。

尝试将成员age的类型更改为 int