我有一個程序根據用戶輸入創建來自兩個不同類的對象。如果用戶是學生,則學生課程的一個對象將被創建,學生將進入他們正在接受的課程。我有一個while
循環,詢問用戶他們每次進入課程後是否想要進入其他課程。如果此用戶n
,這是應該結束循環的條件,程序與exit code 11
停止: C++:遇到環境條件時程序崩潰
這不應該是這樣的。 while循環後有更多的代碼行,並且循環結束後程序不應該結束。這裏是有問題的,而循環功能:
void createStudent (char student_name[], int student_age)
{
Student student;
student.setName(student_name);
student.setAge(student_age);
char courses[8];
char course_loop = ' ';
int count = 0;
cout << "What courses are you taking? "
"(Enter course prefix and number with no spaces):\n\n";
while (tolower(course_loop) != 'n')
{
cout << "Course #" << count + 1 << ": ";
cin.ignore();
cin.getline(courses, 9);
//student.sizeOfArray(); // Increment the array counter if addCourse reports that the array was not full
student.addCourse(courses, count);
cin.clear();
if (student.addCourse(courses, count))
{
cout << "\nHave another course to add? (Y/N): ";
cin.clear();
cin.get(course_loop);
}
else
{
cout << "You have exceeded the number of courses you're allowed to enter. Press any ENTER to continue...";
cin.ignore();
course_loop = 'n';
}
count++;
}
cout << student;
student.printCourseNames();
}
這裏是程序的其餘部分:
// main.cpp
//-----------------------
#include <iostream>
#include "Person.h"
#include "Student.h"
using namespace std;
void createStudent(char [], int);
void createPerson(char [], int);
int main()
{
char name[128], student_check;
int age;
cout << "Please state your name and age: \n\n"
<< "Name: ";
cin.getline(name, 128);
cout << "Age: ";
cin >> age;
cout << "\n\nThanks!\n\nSo are you a student? (Y/N):";
cin.ignore();
cin.get(student_check);
switch (student_check)
{
case 'y':
case 'Y':
createStudent(name, age);
break;
case 'n':
case 'N':
createPerson(name, age);
break;
default:
break;
}
}
// createStudent function with while-loop posted above comes after this in main.cpp
// student.h
// ------------------
#include "Person.h"
#ifndef PA2_STUDENT_H
#define PA2_STUDENT_H
class Student : public Person
{
public:
Student();
bool addCourse(const char*, int);
void printCourseNames();
void sizeOfArray();
private:
const char* m_CourseNames[10] = {0};
int array_counter;
};
#endif
// student.cpp
//------------------
#include <iostream>
#include "Student.h"
using namespace std;
Student::Student() : array_counter(0) {}
void Student::sizeOfArray()
{
array_counter++;
}
bool Student::addCourse(const char* course, int index)
{
if (index < 9)
{
m_CourseNames[index] = course;
return true;
}
else if (index == 9)
return false;
}
void Student::printCourseNames()
{
if (array_counter != 0)
{
cout << ", Courses: ";
for (int count = 0 ; count < 10 ; count++)
cout << m_CourseNames[count] << " ";
}
}
我使用的克利翁爲我的IDE,有沒有什麼幫助。
你的'''重載是什麼樣的? – molbdnilo