我的c ++程序中的char数组不会打印任何内容

时间:2018-03-21 16:26:58

标签: c++ arrays printing char

我正在为我的班级做第一个C ++程序。我对这个项目很陌生,所以我需要学习很多东西。在我的程序中,我想创建一个带有Undergrad / grad / gradassist派生类的Student类。名称和SSN字段必须在char数组中(我知道字符串更有意义,但老师要求char数组)。该程序大多数工作正常,但它不会在我的char数组中打印任何东西。请帮忙!

#include <iostream>;
using namespace std;
class Student {
  protected:
    char name[21];
    char ssn[10];
    float gpa;
    int credits;

  public: 
     Student::Student() {};

     Student(const char n[], const char ss[], float& gp, int& cred) {
      name[21] = n[21];
      ssn[10] = ss[10];
      gpa = gp;
      credits = cred;


  }

    virtual void print() {
     cout << "Name: " << name << endl;
     cout << "SSN: " << ssn << endl;
     cout << "GPA: " << gpa << endl;
     cout << "Credits: " << credits << endl;
 }
    virtual float tuition() const = 0;


 };
class undergrad : public Student {
  protected:
    float undergrad_rate;
    char* year;
  public:
   undergrad::undergrad() {}

   undergrad(float ugr, char* yr, const char n[], const char ss[], float& 
   gp, int& cred) :
   Student(n, ss, gp, cred), undergrad_rate(ugr), year(yr){}

   void set_year(char* yr) {
    year = yr;
                            }
   char* getYear() {
    return year;
      }
   float getRate() {
    return undergrad_rate;
      }
    void print() {
    Student::print();
    cout << "Undergrad rate: " << undergrad_rate << endl;
    cout << "year: " << year << endl;


       }

   float tuition() { 
   //cout << "The tuition is $35000" << endl;
   return 35000;
    }

  };
 class grad : public Student {
  protected:
   float grad_rate;
   char* thesis;

  public:

 };

  int main(){

    char* jr = "Junior";
    char* sr1 = "Senior";
    char* fr = "Freshman";
    char* sr = "Sophmore";

    undergrad g(380, jr, "M", "000111222", 4.0, 12);
    g.print();


    system("pause");
    return 0;

 }

1 个答案:

答案 0 :(得分:1)

问题在于,初始化成员名称 ssn 的方式:

desired_output = b[["Group"]].join(result)
print(desired_output)
#    Group    A    B
#0  group1  7.0  4.0
#1  group1  3.0  2.5
#2  group1  2.2  2.0

这里有不止一件事

  1. name ssn 分别是大小为21和大小为10的char数组。这意味着有效索引的范围分别为0到20和0到9。因此,通过访问 name [21] ssn [10] ,您将访问超出分配内存末尾的元素。
  2. 即使索引有效,您也可以通过这种方式分配单个字符。
  3. 为了按照您的意图初始化这些成员变量,请执行以下操作:

     Student(const char n[], const char ss[], float& gp, int& cred) {
          name[21] = n[21];
          ssn[10] = ss[10];
    

    这会将包含输入字符串的所有字符复制到您的成员变量中,您将获得所需的输出。