2015-09-03 2 views
0

У меня есть программа, которая создает объекты из двух разных классов в зависимости от ввода пользователем. Если пользователь является учеником, объект класса Student будет создан, когда ученик войдет в классы, которые они принимают. У меня есть цикл 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] << " "; 
    } 
} 

Я использую CLion как мой IDE, если это помогает.

+0

Как выглядит ваша '' 'перегрузка? – molbdnilo

ответ

1

Вам нужно добавить функцию, которая может послать Student объект в выходной поток, как cout. Таким образом, что это будет сделано это путем определения функции следующим образом:

ostream& operator<<(ostream& os, const Student& student) 
{ 
    os << "Name: " << student.name << ", Age: " << student.age << ", Courses: " << student.m_CourseNames; 
    return os; 
} 

Эта функция позволяет использовать оператор << для передачи данных в выходной поток, как cout, от вашего Student класса. Он принимает поток вывода как один аргумент, а ученик - другой. Он печатает информацию учащегося, а затем возвращает выходной поток. Это так, что вы можете связать оператора, чтобы сразу печатать несколько фрагментов информации.

+0

Я действительно прокомментировал строку 'cout << student', и я получаю то же сообщение об ошибке. Показ, что перегрузка оператора не является причиной. – jshapy8

1

EDIT: ошибка, связанная с этим возвратом, относится к буфере.

Ваш буфер ввода char courses[8] недостаточно велик для обработки ввода от cin.getline(courses, 9), что вызывает переполнение буфера cin. Перехват cin.clear() восстанавливает входной поток, чтобы разрешить ввод для cin.get(course_loop), но исключение все еще не обрабатывается, когда функция пытается вернуться.

Изменение char courses[8] на char courses[10] (в соответствии с m_CourseNames массив в Student) и он должен работать должным образом.

Обновленный код:

void createStudent(char student_name[], int student_age) 
{ 
    Student student; 

    student.setName(student_name); 
    student.setAge(student_age); 

    char courses[10]; 
    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); 
     cin.clear(); 

     //Removed the duplicate addCourse() call 
     if (student.addCourse(courses, count)) 
     { 
      student.sizeOfArray(); //Needed for printCourseNames() functionality 
      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(); 

    return; 
} 
Смежные вопросы