Name sorting

After complining my program doesn't display result.

[code]
#include <iostream>
#include <string>
#include <fstream>

using namespace std;
// functions protoype

void sortSurnameFirst ( string [], string[], size_t );
void displayNames ( string [], string[], size_t );
void sortFirstNames ( string [], string [], size_t );

int main()
{
int const SIZE = 200;
size_t count = 0;
int choice;

string names[SIZE];
string surnames[SIZE];

ifstream inputFile;
string filename = "names.txt";

inputFile.open(filename.c_str());

if(inputFile)
{

while(count <SIZE && inputFile>>surnames[count] >> names[count])
{
count ++;
}

inputFile.close();

cout << " 1. Sort names by surnames then first names "<<endl;
cout << " 2. Sort names by first names then by surnames "<<endl;
cout<< "Enter your sorting choice " ;
cin >> choice;

if ( choice == 1)
{
cout<< "The names are sorted by surnames then first names"<<endl;
sortSurnameFirst (surnames, names,count);
displayNames(surnames, names,count);
}

if ( choice == 2)
{
cout<< "The names are sorted by first names then surnames"<<endl;
sortSurnameFirst (surnames, names,count);
displayNames(surnames, names,count);
}

}

else
{
cout << " The following file doesnt exist"<<endl;
}



return 0;
}






void sortSurnameFirst ( string surnames[], string names[], size_t size )
{
bool swap;
string sort ;
string temp;
do
{
swap = false;
for ( size_t i =0; i < size ; i++)
{
if ( surnames[i] > surnames[i++] )
{
sort = surnames[i];
surnames[i] = surnames[i++];
surnames[i++] = sort ;
swap = true;


}


if ( surnames[i] == surnames[i++] )
{
if (names[i] > names[i++] )
{
temp= names[i];
names[i] = names[i++];
names[i++] = temp ;
sort = surnames[i];
surnames[i] = surnames[i++];
surnames[i++] = sort ;

swap = true;
}
}



}

}while (swap);
}


void displayNames( string surnames[], string names[], size_t size )
{

for ( size_t i =0; i < size ; i++)
{
cout << surnames[i]<<" " << names[i] << endl;
}
}


void sortFirstNames ( string surnames[], string names[], size_t size )
{
bool swap;
string sort1, temp1;
do
{
swap = false;

for ( size_t i =0; i < size ; i++)
{
if ( names[i] >names[i++] )
{
sort1 = names[i];
names[i] = names[i++];
names[i++] = sort1 ;
swap = true;

}
if ( names[i] == names[i++] )
{
if (surnames[i] > surnames[i++] )
{
temp1 = surnames[i];
surnames[i] = surnames[i++];
surnames[i++] = temp1 ;
sort1 = names[i];
names[i] = names[i++];
names[i++] = sort1 ;
swap = true;
}
}



}

}while (swap);
}





In sortSurnameFirst(...) / sortFirstNames(...): i++ must only appear in the

for ( size_t i =0; i < size ; i++)

loop header, otherwise the index will go out of bounds and the program crashes.

What you meant to do is certainly (e.g.) names[i] == names[i + 1]

Then the loop should be:

for ( size_t i =0; i < size - 1 ; i++)
Topic archived. No new replies allowed.