0
//program to print the sentences in lexicographical order
#include<stdio.h>
#include<string.h>
int main()
{
int n,i,j;
char a[n][20],temp[20];

printf("enter the number of strings");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
    printf("enter the string%d",i);
    fgets(a[i],sizeof(a[i]),stdin);
}
for(i=1;i<n;i++)
{
    for(j=i+1;j<=n;j++)
    {
        if(strcmp(a[i],a[j])>0)
        {
            strcpy(temp,a[i]);
            strcpy(a[i],a[j]);
            strcpy(a[j],temp);
            
        }
        
    }
}
printf("In lexicographical order");
for(i=1;i<=n;i++)
{
    fputs(a[i],stdout);
}
return 0;
}

output:

enter the number of strings4
enter the string1enter the string2raja
enter the string3sekar
enter the string4hari
In lexicographical order
hari
raja
sekar

I have included both input and output. In the output screen it is displaying enterthestring1enterthestring2, I need to get only one sentence enterthestring1. What's the error buddy

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
rajasekar
  • 1
  • 1
  • 1
    In C array indexing is 0-based. Also, you should [Remove the trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221). – Weather Vane Jul 09 '20 at 13:06
  • 1
    `enter the number of strings4` is horrible formatting of your output. Place at least a space between the input demands and the actual output by using `("enter the number of strings ");` or even better add a semicolon `("enter the number of strings: ");`. – RobertS supports Monica Cellio Jul 09 '20 at 13:08
  • the first gets read the rest of the line after "4'" so an empty line – bruno Jul 09 '20 at 13:10
  • Your first input was skipped (actually an empty string). Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). The error is mixing the input methods. So how to you enter the integer? Answer, with `fgets()` and `sscanf()`. – Weather Vane Jul 09 '20 at 13:10
  • just replace `fgets(...)` by `fscanf(" %19[^n]", a[i]);` (the space before '%' is not an error and allows to bypass spaces including newline) – bruno Jul 09 '20 at 13:11
  • note also your way to sort is expensive and can be reduced easily even still in O(n*n), else use `qsort` function – bruno Jul 09 '20 at 13:16

0 Answers0