DO IN C Write a program which will ask the user how many nam
DO IN C++
Write a program, which will ask the user how many names (one word, no spaces) theywish to enter. The program will then read that many names, store them in a twodimensional array of characters (one row per name), print them in the order they wereentered, then sort them in increasing alphabetical order, and print them in sorted order.The sort will be done without regard to the case of the letters (i.e. case insensitive sort).The printing of each name MUST be done with the characters as they were typed, youcannot change the case.
1- The maximum number of names to be handled will be 20.
2- The maximum number of printable characters in a name is 15.
3- Use a two dimensional array to store the names.
4- Create a function to read in all the names.
5- Create a function to do the sort (modify the bubble sort discussed in class and in the textbook).
Along with the .cpp file please also incluede the .h file
Solution
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#define NAMELEN 16
char nameStrings[20][NAMELEN];
char *names[20];
void
readNames(int n)
{
for (int i=0; i<n; i++) {
names[i] = &nameStrings[i][0];
fgets(names[i], NAMELEN, stdin);
}
}
void
writeNames(const char* titleString, int n)
{
printf(\"%s\ \", titleString);
for (int i=0; i<n; i++)
printf(\"%s\", names[i]);
}
int
compareNames(const void*s1, const void*s2)
{
char *p1 = *(char**)s1;
char *p2 = *(char**)s2;
return strncasecmp(p1, p2, NAMELEN);
}
int
main(int argc, char* argv[])
{
char numBuffer[20];
int numNames = 0;
printf(\"How many names?\");
fgets(numBuffer, sizeof(numBuffer), stdin);
numNames = atoi(numBuffer);
if (numNames < 0 || numNames > 20)
printf(\"Number of names must not exceed 20\ \"), exit(-1);
readNames(numNames);
writeNames(\"Original list of names\", numNames);
qsort(names, numNames, sizeof(char*), compareNames);
writeNames(\"\ Sorted list of names\", numNames);
return 0;
}


