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?