Write a C++ program to prompt the user to enter a number of names, then print out all the names in alphabetical order of the last names. If the last names are the same, then the first names are compared. A sample run is attached as follows (the text in bold face is user input):
How many names do you want to enter? 5
Enter name #1: Bill Gates
Enter name #2: Michael Jackson
Enter name #3: Tony Blair
Enter name #4: Janet Jackson
Enter name #5: Oprah Winfrey
The names in order are:
Blair, Tony
Gates, Bill
Jackson, Janet
Jackson, Michael
Winfrey, Oprah
The strings we are using in this program are C-strings. You cannot use C++ strings. And, you cannot use any library function other than the overloaded operator (<< or >>)
What I have tried:
I am stuck on this problem, I am using 2 2d arrays for the last names and first names, I initially planned to make a temp array that would hold the sorted last names and first names after I am done with comparison, however, I can't seem to move any further from here, I am stuck after comparing any help would be much appreciated!
int mystrlen(char* s)
{
int i;
for (i=0; s[i] != '\0'; i++);
return i;
}
int length_longest(char ** name)
{
int max= mystrlen(name[0]);
int j=0;
for(int i=1; i<n; i++)
{
int len = mystrlen(name[i]);
if(max<len)
{
max=len;
j=i;
}
}
return max;
}
int compare (char** string, int n)
{
int max_len=longest_length(string);
for(int j=0; j<max_len; j++)
{
for(int i=0; i<n; i++)
{
if(string[i][j]>string[i+1][j])
return 1;
else if(string[i][j]==string[i+1][j+1])
{
i++;
j++;
}
}
}
}
the main looks something like this:
int main()
{
int n;
cout<<"How many names do you want to enter ? ";
cin>>n;
char** lastname = new char*[n];
for(int i=0; i<n; i++)
lastname[i]=new char[100];
char ** firstname = new char*[n];
for(int i=0; i<n; i++)
firstname[i]=new char[100];
for(int i=0; i<n; i++)
{
cout<<"enter name #"<<i+1 <<" :";
cin>>firstname[i]>>lastname[i];
}
for(int i=0; i<n; i++)
{
cout<<firstname[i]<<" "<<lastname[i];
cout<<endl;
}
}