为什么程序在调用函数时会跳过输入?

时间:2016-02-28 14:00:08

标签: c++ eclipse

我正在编写一个简单的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,如输出中所示 - &gt;这是因为我按了回车吗?。

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

1 个答案:

答案 0 :(得分:0)

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

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