CS 250 Computer Programming and Problem Solving - FALL 1998 |
---|
[ Home | Syllabus | Notes | Glossary | CS250 WEB Version Home Page ]
//******************************************** // Read a file of Persons and create a list // Uses template class // // Programmer: Chris Wild //******************************************** #include "person.h" #include "tlist.h" void main() { Tlist<Person> myList; Person someBody; ifstream aFile("persons.txt"); while(aFile >> someBody) { myList.InsertAfter(someBody); } if(!myList.IsEmpty()) { // loop we saw earlier in Using List Objects myList.GoTop(); while(myList.Advance()) { cout << myList.Get(); } } }
But how to create a lot of data for testing this progam?
Generating a file by hand is tedious - let's look at generating the data with a program.
#include <stdlib.h> // for srand/rand #include <time.h> // for time #include "Person.h" #include "fixedstring.h" #include <fstream.h> // prototypes FixedString genName(); // returns a fixed string object resembling a name which is generated at random FixedString genSSN(); // returns a fixed string object resembling a SSN which is generated at random int genAge(); // returns an age const int NPersons = 10; // Number of Person records to create void main() { ofstream outFile("persons.txt"); Person someBody; srand( (unsigned)time( NULL ) ); for(int i=0; i< NPersons;i++) { someBody.SetFirstName(genName()); someBody.SetLastName(genName()); someBody.SetSSN(genSSN()); someBody.SetAge(genAge()); outFile << someBody; // must be in format that >> can read (made some changes to Person } } // Define random generating functions FixedString genName() // returns a fixed string object resembling a name which is generated at random { int size = rand()%17 + 3; // randomly pick a size between 3 and 19 characters char cString[21]; // allocate space for a C-style string for(int i = 0; i < size; i++) { cString[i] = char(rand()%26 + int('a')); } cString[size] = '\0'; FixedString temp(cString); return temp; } FixedString genSSN() // returns a fixed string object resembling a SSN which is generated at random { int size = 9; // nine digits char string[10]; // allocate space for a C-style string for(int i = 0; i < size; i++) { string[i] = char(rand()%10 + int('0')); } string[size] = '\0'; FixedString temp(string); return temp; } int genAge() // returns an age which increases from 1, 1 at a time { static int nextAge = 1; return nextAge++; // return next number in sequence //return rand()%100; // or could generate at random up to 100 }