1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
|
/* This file will take a persons details and
output them as a student object using fstream */
/* Program failure, compiles and links fine, opens
the cmd line and runs through the switch but when
I start to enter the first and last names it causes
a system error and cmd window has to close.
I did try adding error checks but since none of them
made any difference I took them out */
#include <iostream.h>
#include <fstream.h>
#include <string.h>
// Global function to copy strings, saves time later
char* copyname(char* psA) {
char* psN = new char[strlen(psA) +1];
strcpy(psN, psA);
return psN;
}
// Class will take 4 variables for output.
class Person {
public:
Person(char* psFN, char* psLN, short grade, int number) {
psFname = copyname(psFN);
psLname = copyname(psLN);
year = grade;
ID = number;
}
// Copy constructor
Person(Person&p) {
psFname = copyname(p.psFname);
psLname = copyname(p.psLname);
year = p.year;
ID = p.ID;
// Default constructor
Person() {
psFname = copyname("Invalid");
psLname = copyname("Invalid");
year = 0;
ID = 0;
}
virtual ~Person() {
delete psFname;
delete psLname;
}
// Function I use to format data in text file
void save(ostream& out) {
out << psFname << " "
<< psLname << " "
<< year << " "
<< ID << "\n";
}
protected:
char* psFname;
char* psLname;
short year;
int ID;
};
// Function that will write data to the text file.
void savetostore(char* filename, Person& man) {
ofstream o(filename);
// I have tried using 'Person' pointers, objects and now a reference
// For a pointer other parts of the code have to be changed
Person& m = man;
m.save(o);
if (o.fail()) {
cout << "Couldn't output the object to file" << endl;
}
}
// Function takes the input for creating the object
Person process() {
char* first;
char* last;
short yr;
int iden;
first = "blank";
last = "blank";
cout << "Enter in the following order: "
<< "First and last names, school year and ID" << endl;
cin >> first >> last >> yr >> iden;
Person ppZ(first,last,yr,iden);
return ppZ;
}
int main() {
Person guy;
char alpha;
short loop = 1;
// Using a loop to enter more than one student per run
cout << "Enter either D to store details or X to quit\n";
while(loop) {
cin >> alpha;
switch(alpha) {
case 'd':
case 'D': guy = process();
savetostore("people.txt", guy);
case 'x': loop = 0; break;
case 'X': loop = 0; break;
default: cout << "D or X!\n";
}
}
return 0;
}
|