So for this program I have to have the user input 10 strings. Then the menu asks them how they would like their strings outputted. The first two options (which are print the way they were input, and print in reverse order from how they were input) I have working properly. It's the third option that is giving me trouble.
I need to print their strings descending from longest to shortest.
i.e. if they input:
aaa
b
cccccc
dd
it will output:
cccccc
aaa
dd
b
The function I am using to do this is incorrect and I'm a bit lost now.
Here is my code:
Code:
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<stdlib.h>
_Bool readLine(char *str, int maxLen);
int array_compare(const void *a, const void *b);
int main ()
{
char strs[10][80];
int numStrs=0;
int choice;
int i;
for (i=0; i<10; ++i)
{
readLine(strs[i], 80);
}
do
{
printf("1) Print list of strings in the order input.\n");
printf("2) Print list of strings in the reverse order input.\n");
printf("3) Print list of strings in order of length.\n");
printf("4) Quit\n");
scanf("%d", &choice);
if(choice==1) //print strings in order of input
{
for (i=0; i<10; ++i)
printf("%s", strs[i]);
printf("\n");
}
if(choice==2) //print strings in reverse order of input
{
for (i=9; i>=0; --i)
printf("%s", strs[i]);
printf("\n");
}
if(choice==3) //print strings in order of length
{
qsort(strs, 10, sizeof(char), array_compare);
for(i=0; i<10; ++i)
printf("%s", strs[i]);
printf("\n");
}
}
while(choice!=4 || choice <=0);
}
_Bool readLine(char *str, int maxLen) //read in strings
{
int i=0;
int c = 'a';
for(i=0; c!='\n' && i<maxLen-1; ++i)
{
c= getchar();
if(c==EOF)
break;
str[i]=c;
}
str[i]='\0';
}
int array_compare(const void *a, const void *b) //order strings by length
{
const int *pa = (const int*)a;
const int *pb = (const int*)b;
return *pa - *pb;
}
If anyone can show me how my function should look I would really appreciate it!! Thanks in advance!