I have been struggling to write a simple code to sort an array of char in C and been failing miserably. This is what I have so far:
int main()
{
char line[128];
char word[128];
int i=0;
int j;
int length;
while(fgets(line,sizeof line,stdin) != NULL)
{
length=0;
i=0;
while (line[i]!='\0')
i++;
length=i;
line[i-1]=line[i];
for (i=0;i<=length;i++)
word[i]=line[i];
for (i=length-1; i>=0; i--)
{
for (j=0;j<i;j++)
{
if (line[j] > line[i])
{
char temp;
temp=line[j];
line[j]=line[i];
line[i]=temp;
}
}
}
printf("%s %s\n",line,word);
}
return 0;
}
Original file:
overflow
array
test
string
stack
Output file:
overflow
array
test
string
stack
This is giving me rather unexpected results. Where am I going wrong?
Change:
to:
and it works.
When you do
line[i-1] = line[i];you are removing the\n(which is placed there byfgets) from the line and effectively reducing the string length by 1. You should take that into account.With your current code, the length includes the null terminator, which gets sorted to the beginning of the string, hence your result is an empty string.