开发者

Sort an array of char in C

I have bee开发者_JAVA百科n 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:

length = i;

to:

length = i - 1;

and it works.

When you do line[i-1] = line[i]; you are removing the \n (which is placed there by fgets) 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.


Just as I suspected, by avoiding the CR/LF:

length=i;
line[i-1]=line[i];

you included the '\0' characted in the string to be sorted. It will get in the first place, so you'll have an empty string to print.


You are removing the \n from the line by overwriting it with \0 but your length calculation is done before this change.

To fix this, do

line[i-1]=line[i];

before you calculate the length.

Since your length is one more than the actual length, \0 is also taking part as a char to be sorted and since its the smallest of all char, it gets placed at the beginning of the string, effectively making your string empty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜