debug醒目 ssd5醒目
//main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
#include "course.h"
#include "safearray.h"
void init_courses(safearray<course>);
void display_menu(safearray<course>);
const int NUM_COURSES = 10;
const int QUIT = 99;
int main(int argc, char* argv[])
{
safearray<course> courses(NUM_COURSES);
init_courses(courses);
int choice = 0;
while (choice != QUIT)
{
display_menu(courses);
cout << "Enter number of course to see more information on\n";
cin >> choice;
cout << "\n";
if (choice >= 1 && choice <= NUM_COURSES)
{
cout << courses[choice - 1] << "\n\n";
}
cout<<"a"<<endl;
}
return EXIT_SUCCESS;
}
void display_menu(safearray<course> courses)
{
for (int i = 1; i <= NUM_COURSES; i++)
{
cout << i << ". " << courses[i - 1].name << "\n";
}
cout << "99. Quit\n";
}
void init_courses(safearray<course> courses)
{
ifstream inf("courses.txt");
if (! inf)
{
cerr << "Could not open courses.txt" << endl;
exit(EXIT_FAILURE);
}
for (int i = 0; i < NUM_COURSES; i++)
{
inf >> courses[i];
}
inf.close();
}
//safearray.h
#ifndef SAFEARRAY_H
#define SAFEARRAY_H
template <class T>
class safearray {
private:
T *storage;
int capacity;
public:
safearray() : storage(NULL), capacity(0) {} // default constructor
safearray(int size)
{
storage= new T[size];
capacity=size;
}
~safearray(void){delete []storage ;}
T& operator[] (int i) throw(out_of_range)
{
if(i<0)
throw(out_of_range)("err: input < 0");
else if(i>capacity)
throw(out_of_range)("err: input > max");
else
return *(storage+i);
}
};
#endif
//course.h
#ifndef COURSE_H
#define COURSE_H
int const MAX_LINES = 10;
class course {
public:
string name;
string title;
string description[MAX_LINES];
course() : name(""), title("") {}
course(string name, string title) :
name(name), title(title) {}
friend ostream& operator<<(ostream&, const course&);
friend istream& operator>>(istream&, course&);
};
ostream& operator<<(ostream& out, const course& c) {
out << c.name << ": " << c.title << "\n";
int index = 0;
while (c.description[index] != "") {
out << c.description[index++] << "\n";
}
return out;
}
istream& operator>>(istream& in, course& c) {
getline(in, c.name);
getline(in, c.title);
string line;
getline(in, line);
int number = 0;
while (line != "") {
c.description[number++] = line;
getline(in, line);
}
return in;
}
#endif