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
|
// Ex11_02.cpp : Extending the test operation
#include <iostream>
#include <stdlib.h>
#include <crtdbg.h>
#include <cstdio>
#include "Name.h"
using namespace std;
// Function to initialize an array of random names
void init(Name* names, int count)
{
char* firstnames[] = { "Charles", "Mary", "Arthur", "Emily", "John"};
int firstsize = sizeof (firstnames)/sizeof(firstnames[0]);
char* secondnames[] = { "Dickens", "Shelley", "Miller", "Bronte", "Steinbeck"};
int secondsize = sizeof (secondnames)/sizeof(secondnames[0]);
char* first = firstnames[0];
char* second = secondnames[0];
for(int i = 0 ; i<count ; i++)
{
if(i%2)
first = firstnames[i%firstsize];
else
second = secondnames[i%secondsize];
*(names+i) = Name(first, second);
}
}
int main(int argc, char* argv[])
{
FILE *pOut(nullptr);
errno_t err = freopen_s( &pOut, "debug_out.txt", "w", stdout );
if(err)
cout << "error on freopen" << endl;
_CrtSetDbgFlag( _CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF );
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
Name myName("Ivor", "Horton"); // Try a single object
// Retrieve and store the name in a local char array
char theName[12];
cout << "\nThe name is " << myName.getName(theName);
// Store the name in an array in the free store
char* pName = new char[myName.getNameLength()+1];
cout << "\nThe name is " << myName.getName(pName);
const int arraysize = 5;
Name names[arraysize]; // Try an array
// Initialize names
init(names, arraysize);
// Try out comparisons
char* phrase = nullptr; // Stores a comparison phrase
char* iName = nullptr; // Stores a complete name
char* jName = nullptr; // Stores a complete name
for(int i = 0; i < arraysize ; i++) // Compare each element
{
iName = new char[names[i].getNameLength()+1]; // Array to hold first name
for(int j = i+1 ; j<arraysize ; j++) // with all the others
{
if(names[i] < names[j])
phrase = " less than ";
else if(names[i] > names[j])
phrase = " greater than ";
else if(names[i] == names[j]) // Superfluous - but it calls operator==()
phrase = " equal to ";
jName = new char[names[j].getNameLength()+1]; // Array to hold second name
cout << endl << names[i].getName(iName) << " is" << phrase
<< names[j].getName(jName);
delete[] jName;
}
delete[] iName;
}
delete[] pName;
cout << endl;
return 0;
}
|