为什么在类中使用字符串会导致分段错误?

时间:2019-02-20 05:33:46

标签: c++

我有一个叫做Student的班级,

    Student AddStudent(Student *newStudent, int &countStudent, int &numStudent)
    {
        std::string tempName;
        //Create a a new temporary object of class student to hold the value of ID and name
        Student tempStudent;
        cout << "Please enter student id: ";
        cin >> tempStudent.studentID;
        cout << "Please enter student name: ";
        getline(cin, tempName);
        tempStudent.setName(tempName);
        cin.ignore();
        /*After getting the value from the user, assign the value to class array's element according to the numStudent variable
        then increase the total student to 1.*/
        newStudent[numStudent] = tempStudent;
        numStudent++;
if (numStudent == countStudent)
    {
        //Calling the function to increase our array's size each time a new student is added. 
        newStudent[numStudent] = IncreasingSize(newStudent, countStudent, countStudent + 1);
        //IncreasingSize(newStudent, countStudent, countStudent + 1);
        countStudent += 1;
    }
}

Student IncreasingSize(Student *newStudent, int oldSize, int newSize)
{
    //Create a new pointer array with a size 1 bigger than the old one. Ex: If last array size is 1, then new array size is 2
    Student *newStudentSize = new Student[newSize];
    for (int i = 0; i < oldSize; i++)
    {
        //Copy all data from old array to new array 
        newStudentSize[i] = newStudent[i];
    }
    /*Return new array*/
    return *newStudentSize;
}

和我的Student.cpp

    int numStudent = 0;
    int i, j, countStudent = 1;
    Student *newStudent = new Student[countStudent];//Create a class pointer array with dynamic memory
AddStudent(newStudent, countStudent, numStudent);
This is how I print my class array:
printf("%-15s %-15s\n", "Student ID", "Student Name");
            for (i = 0; i < numStudent; i++)
            {
                //printf("%-15d %-20s\n", newStudent[i].studentID, newStudent[i].studentName);
                cout << newStudent[i].studentID << "\t" << newStudent[i].studentName << "\n";
            }

这是我的主要程序,它调用AddStudent函数:

{{1}}

在我的主菜单中,我将调用此函数以将新学生添加到班级数组中。我在这里遇到的问题是,如果我使用字符串,无论出于何种原因,都会导致分段错误。但是,如果我将char数组用于诸如“ char studentName [50]”之类的studentName并使用cin来获取其值,则一切运行都会很顺利。

char的坏处是我无法使用getline获取空间值,就像到达空间时停止一样。如果我想在课堂上使用字符串,有什么办法可以解决此问题? 谢谢您的帮助。

0 个答案:

没有答案