Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将C转换为C++;和动态内存分配 因此,我最近被安排将C语言编写的程序转换成C++,以便在编程课程中完成作业。该程序是一个基本的数据库程序,用户可以在其中创建一个带有学生ID、文本名称、课程ID、文本名称和成绩的成绩册。用户将能够与菜单交互并执行许多操作。最重要的是,该程序可以在需要时重新分配更多内存,并且会自动执行此操作。所以现在,我试图把这个程序转换成C++。p> 我们在课堂上讨论了大约两个半星期的C++,所以我对语言还很陌生。我已经为这个项目提供了一个片段,以及我所做的一切,以便你们能够更好地理解我的问题。我已经包含了课程类和两个函数(第一个添加课程ID和文本名称,第二个打印课程的完整列表)。我希望绑定从25开始,如果用户希望在超过此绑定后加入更多课程,程序将分配更多内存并将旧条目复制到新空间。我不确定我是否仍然不理解构造函数或者什么,但是每当用户输入第26个课程时,它就不会被保存。如果我试图在这种情况下打印课程,就会出现分割错误_C++_C - Fatal编程技术网

将C转换为C++;和动态内存分配 因此,我最近被安排将C语言编写的程序转换成C++,以便在编程课程中完成作业。该程序是一个基本的数据库程序,用户可以在其中创建一个带有学生ID、文本名称、课程ID、文本名称和成绩的成绩册。用户将能够与菜单交互并执行许多操作。最重要的是,该程序可以在需要时重新分配更多内存,并且会自动执行此操作。所以现在,我试图把这个程序转换成C++。p> 我们在课堂上讨论了大约两个半星期的C++,所以我对语言还很陌生。我已经为这个项目提供了一个片段,以及我所做的一切,以便你们能够更好地理解我的问题。我已经包含了课程类和两个函数(第一个添加课程ID和文本名称,第二个打印课程的完整列表)。我希望绑定从25开始,如果用户希望在超过此绑定后加入更多课程,程序将分配更多内存并将旧条目复制到新空间。我不确定我是否仍然不理解构造函数或者什么,但是每当用户输入第26个课程时,它就不会被保存。如果我试图在这种情况下打印课程,就会出现分割错误

将C转换为C++;和动态内存分配 因此,我最近被安排将C语言编写的程序转换成C++,以便在编程课程中完成作业。该程序是一个基本的数据库程序,用户可以在其中创建一个带有学生ID、文本名称、课程ID、文本名称和成绩的成绩册。用户将能够与菜单交互并执行许多操作。最重要的是,该程序可以在需要时重新分配更多内存,并且会自动执行此操作。所以现在,我试图把这个程序转换成C++。p> 我们在课堂上讨论了大约两个半星期的C++,所以我对语言还很陌生。我已经为这个项目提供了一个片段,以及我所做的一切,以便你们能够更好地理解我的问题。我已经包含了课程类和两个函数(第一个添加课程ID和文本名称,第二个打印课程的完整列表)。我希望绑定从25开始,如果用户希望在超过此绑定后加入更多课程,程序将分配更多内存并将旧条目复制到新空间。我不确定我是否仍然不理解构造函数或者什么,但是每当用户输入第26个课程时,它就不会被保存。如果我试图在这种情况下打印课程,就会出现分割错误,c++,c,C++,C,如果有人能发现我做错了什么,我将不胜感激。如果有什么我没有说清楚的,请告诉我,我会尽快回复。谢谢大家花时间看我的节目 #include <iostream> #include <fstream> #include <stdlib.h> #include <string> using namespace std; const int MAX_COURSES=25; //Class class Course { //Two private

如果有人能发现我做错了什么,我将不胜感激。如果有什么我没有说清楚的,请告诉我,我会尽快回复。谢谢大家花时间看我的节目

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>

using namespace std;

const int MAX_COURSES=25;

//Class
class Course
{
    //Two private member variables
    private:
          string courseText;
          int courseID;

    public:
    //Constructor
      Course(void);

    //Member functions
      static void addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);
      static void printCourses(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);

};

//Class implementation
//Constructor
Course::Course(void)
{
    //Just providing initial value to the two object variables
    courseText;
    courseID=-1;
}

//This function isn't a part of any class and will print the grade book menu.
void printMenu()
{
    cout << endl;
    cout << "GRADE BOOK MENU" << endl;
    cout << "1. Add a new course" << endl;
    cout << "2. Add a new student" << endl;
    cout << "3. Add a student to a course" << endl;
    cout << "4. Add grades for a student in a course" << endl;
    cout << "5. Print a list of all grades for a student in a course" << endl;
    cout << "6. Print a list of all students in a course" << endl;
    cout << "7. Compute the average for a student in a course" << endl;
    cout << "8. Print a list of all courses" << endl;
    cout << "9. Print a list of all students" << endl;
    cout << "10.    Compute the average for a course" << endl;
    cout << "11.    Store grade book (to a disk file" << endl;
    cout << "12.    Load grade book (from a disk file" << endl;
    cout << "13.    Quit the program" << endl;
    cout << "14. Check individual student 2D grade matrix" << endl;
    cout << endl;
}


//This method function will add a course to the course list
void Course::addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter)
{
    int userEnteredCourseID=0;
    Course* pointerCourses=NULL;
    pointerCourses = courses;
    do
    {   

    cout << endl;
    cout << "Please enter a course ID number using only integers." << endl;
    cout << "There is a limit of only 25 courses allowed in the grade book." << endl;
    cout << "To exit to grade book menu at any time, enter a negative integer or 0." << endl;
    cout << "A message will be returned to you and no course IDs will be added." << endl;   

    cin >> userEnteredCourseID;

    //Checking for a valid integer input.
    while(cin.fail())
    {
        cout << "Error! User entered something other than an integer." << endl;
        cin.clear();
        cin.ignore(256,'\n');
        cout << "Try entering a valid integer input this time..." << endl;
        cin >> userEnteredCourseID;
        }
    cout << "You have entered the integer " << userEnteredCourseID << endl;

    /*Checking if they entered a negative integer value.*/
    if(userEnteredCourseID<=0)
    {
        cout << endl;
        cout << "You have entered a negative integer or 0. Nothing has been added" << endl;
        cout << "to the course list and you will be returned to the menu." << endl;
    }

    /*A valid integer was entered.*/
    else
    {
        /*Now need to check if the course has been entered before. Should be noted, only
        course ID numbers will be checked, not text names. Two course IDs could exist for
        the same course; these ID numbers could represent different times for the same 
        course.*/

        int j;

        for(j=0; j<MAX_COURSES+(*timesReallocatedCoursesCounter); j++)
        {   
            /*Checks if user has entered that course ID before.*/
            if(courses[j].courseID==userEnteredCourseID)
            {
                cout << "You've already entered that course ID!" << endl;
                userEnteredCourseID=0;
                break;
            }

            /*If the current element doesn't equal the course ID entered, keep traversing the array.*/
            else if(courses[j].courseID!=userEnteredCourseID && j<=((MAX_COURSES + (*timesReallocatedCoursesCounter))-2))
            {
                continue;
            }

            /*Entire loop was traversed and there weren't any duplicate course IDs, so a new course will be added to array.*/   
            else
            {
                //Since the previous bounds for courses used to be 25, we'll leave that part of the code in.
                    //However, since we now want to allow for infinite inputs, if the user reaches 25
                    //courses, the program will reallocate memory and allow for more courses to be entered.
                    //Only memory space for one course will be allocated each time so space isn't wasted.
                    if(*courseCounter==(MAX_COURSES + (*timesReallocatedCoursesCounter)))
                    {
                            courses = new Course[MAX_COURSES + *timesReallocatedCoursesCounter + 1];

                    for(int m=0; m < MAX_COURSES + *timesReallocatedCoursesCounter; m++)
                    {
                        courses[m] = pointerCourses[m];
                    }

                    delete[] pointerCourses;
                            *timesReallocatedCoursesCounter+=1;
                    courses[*courseCounter].courseID=userEnteredCourseID;
                                    cout << "What would you like the new course to be called?" << endl;
                                    cin.ignore();
                                    getline(cin, courses[*courseCounter].courseText);
                                    cout << "Course " << userEnteredCourseID << " has successfully been registered with the name " << courses[*courseCounter].courseText << endl;
                                    *courseCounter+=1;
                                    cout << "Press enter to continue." << endl;
                                    cin.ignore();
                }

                else
                {

                    courses[*courseCounter].courseID=userEnteredCourseID;
                    cout << "What would you like the new course to be called?" << endl;
                    cin.ignore();
                    getline(cin, courses[*courseCounter].courseText);
                    cout << "Course " << userEnteredCourseID << " has successfully been registered with the name " << courses[*courseCounter].courseText << endl;
                    *courseCounter+=1;
                    cout << "Press enter to continue." << endl;
                    cin.ignore();
                }
            }
        }   
    }

    }while(userEnteredCourseID>0);

}

//This method function prints the courses that have been successfully entered by the user.
void Course::printCourses(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter)
{
    if(*courseCounter==0)
    {
        cout << endl;
        cout << "You haven't entered any course IDs successfully yet!" << endl;
    }

    else
    {
        int i;
        cout << endl;
        cout << *courseCounter << " course(s) successfully entered so far." << endl;
        cout << "The gradebook started with allowing only 25 courses to be entered." << endl;
        cout << "Due to the amount of courses entered by the user, memory has been reallocated" << endl;
        cout << *timesReallocatedCoursesCounter << " time(s) (in increments of 1) so entries could be made." << endl;
        cout << "This means, a maximum of " << MAX_COURSES+*timesReallocatedCoursesCounter << " courses can be entered before reallocation is needed." << endl;
        cout << "The list of the courses entered so far are:" << endl;
        for(i=0;i<*courseCounter;i++)
        {
            cout << endl;
            cout << courses[i].courseID << ": " << courses[i].courseText;
        }
        cout << endl;
    }
}

//Main program file.
int main(void)
{
    Course *courses;
    courses = new Course [MAX_COURSES];

    int userInput;
    int courseCounter = 0;
    int timesReallocatedCoursesCounter = 0;

    do
    {   
        /*Function that will re-print grade book menu.*/
        printMenu();    
        cout << "What would you like to do with the menu?" << endl;
        cin >> userInput;
            while(cin.fail())
        {
            cout << "Error! User entered something other than an integer." << endl;
            cin.clear();
            cin.ignore(256,'\n');
            cout << "Try entering a valid integer input this time..." << endl;
            cin >> userInput;
            }
        cout << "You have entered the integer " << userInput << endl;

        if(userInput==1)
        {
            cout << "You want to add a new course." << endl;
            Course::addCourse(courses, &courseCounter, &timesReallocatedCoursesCounter);
        }

        else if(userInput==2)
        {
            cout << "You want to add a new student." << endl;
        }

        else if(userInput==3)
                {
                        cout << "You want to add a student to a course." << endl;
                }

        else if(userInput==4)
                {
                        cout << "You want to add a grade for a student in a course." << endl;
                }

        else if(userInput==5)
                {
                        cout << "You want to print the grades for a student in a course." << endl;
                }

        else if(userInput==6)
                {
                        cout << "You want to print a list of students in a course." << endl;
                }

        else if(userInput==7)
                {
                        cout << "You want to compute the average for a student in a course." << endl;
                }

        else if(userInput==8)
                {
                        cout << "You want to print a list of all courses." << endl;
            Course::printCourses(courses, &courseCounter, &timesReallocatedCoursesCounter);
                }

        else if(userInput==9)
                {
                        cout << "You want to print a list of all students." << endl;
                }

        else if(userInput==10)
                {
                        cout << "You want to compute the average for a course." << endl;
                }

        else if(userInput==11)
                {
                        cout << "You want to store the grade book you've been working on to a text file." << endl;
                }

        else if(userInput==12)
                {
                        cout << "You want to load a grade book you've worked on previously from a text file." << endl;
                }

        else if(userInput==13)
                {
                        cout << "You want to quit the program." << endl;
            cout << "Goodbye, and thank you for using this program!" << endl;
                }

        else if(userInput==14)
                {
                        cout << "An optional menu function that prints an individual student's 2D array." << endl;
            cout << "This array contains all the course IDs for which the student is enrolled on the top row." << endl;
            cout << "The rows below the course IDs correspond to grades made by the student in each course." << endl;
        }

        else
        {
            cout << "User entered an integer value that doesn't correspond to any menu option." << endl;
            cout << "Nothing will happen." << endl;
        }

    }while(userInput!=13);

    delete[] courses;

    return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
const int MAX_COURSES=25;
//阶级
班级课程
{
//两个私有成员变量
私人:
字符串courseText;
int courseID;
公众:
//建造师
课程(无效);
//成员函数
静态void addCourse(Course*courses,int*courseCounter,int*TimesRealLocatedCourseSCenter);
静态无效打印课程(课程*课程,整数*课程计数器,整数*时间重新定位课程中心);
};
//类实现
//建造师
课程::课程(无效)
{
//只是为两个对象变量提供初始值
课程文本;
courseID=-1;
}
//此函数不是任何类的一部分,它将打印成绩册菜单。
无效打印菜单()
{
库特
但是每当用户输入第26个

也许是因为这个原因:

const int MAX_COURSES=25;
//...
Course *courses;
courses = new Course [MAX_COURSES]
您为25名学生分配了房间,而不是26名。但是,如果您仅使用阵列,则会出现此问题:

Course courses[MAX_COURSES];
使用数组时,您可能崩溃了,但问题是相同的--内存覆盖。因此,要么决定--将用户限制为25个学生,要么允许任意数量的学生。如果是后者,则需要使用动态数组

最重要的是程序在需要时可以重新分配更多的内存,它会自动完成。所以现在,我尝试把这个程序转换成C++。 <如果使用动态数组,学习使用<代码> STD::vector < /C> >而不是使用<代码> []/DELL[]/COD>将是有利的。这是使用C++实现动态数组的方法。如果您改为使用<代码>新[]/DELL[]/COD>来尝试调整大小,我只能告诉您“好运”。。我几乎可以打赌,如果您选择
new[]/delete[]
路径,您会遇到更多问题

向量方法看起来是这样的:

#include <vector>
//...
typedef std::vector<Course> CourseVector;
//...
void addCourse(CourseVector& v)
{
    Course tempCourse;
    // gather all the user information in tempCourse
    //...
    // now add the course to the array
    v.push_back(tempCourse);
}
static Course* addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);
#包括
//...
typedef std::向量CourseVector;
//...
无效添加课程(CourseVector&v)
{
课程-临时课程;
//收集课程中的所有用户信息
//...
//现在将课程添加到数组中
v、 推回(临时课程);
}

只需一行代码就可以将课程添加到向量中。向量只不过是动态数组的包装器。它基本上执行new[]/delete[]但是它有一个巨大的优势——它正确地使用了这些操作。做这项工作时,你永远不需要弄脏你的手,也不需要犯错误。向量知道什么时候分配,什么时候销毁等等。你所需要做的就是调用函数来调整大小(),推回()等。

我认为您的问题是您正在通过值传递
课程
指针。也就是说,在调用堆栈上创建了
课程
的新副本,您正在对该副本进行操作。
添加课程()
已执行。因此,对于您添加的前25个课程,您的程序工作正常,因为
课程
指针的副本指向与“原始”相同的内存块。当您试图通过分配新的较大内存块来动态增加
课程的大小时,您没有对
main()
中的原始指针执行任何操作。这就是为什么我认为您在打印列表时出错的原因

一种可能的解决方案是让
addCourse()
返回较大的数组,在
main()
中将其设置为
courses
,然后取消分配旧数组

新的
addCourse()
函数的原型如下所示:

#include <vector>
//...
typedef std::vector<Course> CourseVector;
//...
void addCourse(CourseVector& v)
{
    Course tempCourse;
    // gather all the user information in tempCourse
    //...
    // now add the course to the array
    v.push_back(tempCourse);
}
static Course* addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);
在函数内部,使用一个新的
Course
指针分配较大的数组,并将值逐个复制到新数组中。然后,返回新数组

要调用它,请使用如下语句:

Course* newCourses = addCourse(...);
delete [] courses;
courses = newCourses;

不知道为什么代码看起来如此草率。在我的编译器中,空格在很多地方都没有关闭。很抱歉,这就是制表符。将它们转换为空格(使它们成为制表符的编辑器应该有一个选项)然后粘贴到这里。哦,我肯定必须允许输入任意数量的学生。这就是为什么我要进行动态内存分配。到目前为止,我们只学习了new[]和delete[]的功能。boo。我认为他确实分配了新的空间(一个容量为+1的新课程阵列)在他的addCourse函数中。代码太多了,我没有机会全部看一看。但我的答案的最后一部分是——为什么不使用std::vector?@user326