【发布时间】:2015-11-29 13:39:26
【问题描述】:
我有一个程序可以根据用户输入从两个不同的类创建对象。如果用户是学生,将创建 Student 类的对象,学生将在其中输入他们正在学习的课程。我有一个while 循环,询问用户是否想在每次进入课程后进入另一个课程。如果人员键入n,这是应该结束循环的条件,程序会以exit code 11 停止:
情况不应该如此。 while循环后面的代码行比较多,循环结束后程序不应该结束。这是带有问题的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] << " ";
}
}
如果有帮助,我正在使用 CLion 作为我的 IDE。
【问题讨论】:
-
你的
<<重载是什么样的?
标签: c++ class while-loop crash conditional-statements