I have written the below code to sort strings in alphabetical order.But I m unable to understand how fgets is working here.
#include<stdio.h>
#include<string.h>
int main()
{
char s[10][15];
int n;
printf("enter the no of names\n");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
fgets(s[i],15,stdin);
//scanf("%s",s[i]);
}
for(int i=1;i<n;i++)
{
for(int j=0;j<n-i;j++)
if(strcmp(s[j],s[j+1])>0)
{
char g[15];
strcpy(g,s[j]);
strcpy(s[j],s[j+1]);
strcpy(s[j+1],g);
}
}
printf("the sorted strings are");
for(int i=0;i<n;i++)
printf("%s",s[i]);
return 0;
}
If I use scanf instead of fgets to accept strings, n words are accepted but when I'm using fgets for same purpose instead of scanf, n-1 words are accepted. Why is it so?
Is fgets placing last newline character in the nth place?