冒泡排序矩阵以按升序获取一些字符

Bubble sorting a matrix to get some characters in ascending order

我有一个名为 testing.txt 的文件,其中包含以下字符矩阵:

h 3 l l 0 t h
3 r 3 h 0 w a
r e y 0 u d 0
1 n g 2 d a y

使用问题末尾的代码,我将字符分成两个列表,名称如下:numberscharacters 以便我可以在屏幕上打印它们如下(首先是数字,然后是字母):

0 0 0 0 1 2 3
3 3 h l l t h
r h w a r e y
u d n g d a y

请注意,我希望数字按升序显示,而字母我希望它们与矩阵中的原始顺序保持一致。

我的问题:除了数字的顺序外,一切正常。意思是,数字在代码中被排序,但是当我在屏幕上打印矩阵时,我只得到这个:

h l l t h r
h w a r e y
u d n g d a
y

所以数字丢失了。我该如何解决这个问题?

#include <stdio.h>
#include <stdlib.h>
#include <string.h> 

int main()
{

FILE *fich;
char c = 'f', *characters = NULL, *numbers = NULL, *final_list = NULL, aux = 'a';
int character = 0, number = 0, i = 0, j = 0, rows = 1, columns = 0;

fich = fopen("testing.txt", "r");

/*Check if file is available*/

if(fich == NULL)
{
   puts("The file couldn't be opened");
   return 1;
}

/*Allocate dynamic memory*/

characters = (char*) calloc(character, sizeof(char));
numbers = (char*) calloc(number, sizeof(char));

/*Save the list of characters and numbers*/

rewind(fich);

number = character=0;

while ((c = fgetc(fich)) != EOF)
{
   if (c >= 'a' && c <= 'z')
   {
      *(characters+number) = c;
      number++;
   } else if (c >= '1' && c <= '9')
      {
         *(numbers+character) = c;
         character++;
      } else if (c == '\n') 
         {
            rows++;
         }
} 

fclose(fich); 
fich = NULL;

/*Order the lists*/

for (i = 0; i < (number-1); ++i)
{
   for (j = i+1; j < number; ++j)
   {
      if (*(numbers+i)>*(numbers+j))
      {
         aux = *(numbers+j);
         *(numbers+j) = *(numbers+i);
         *(numbers+i) = aux;
      }
   }
}

/*Concat the lists*/

final_list = (char*) calloc((number+character), sizeof(char));

strcat(final_list, numbers);
strcat(final_list, characters);

/*Print the new matrix*/

columns = (number+character)/rows;

for (i = 0; i < (number+character); ++i)
{  
   printf("%c ", *(final_list+i));
   if ((i+1)%columns == 0)
         printf("\n");
}

return 0;
}

您在用于读取文件的 while 循环中交换了 numbercharacter 计数器。改成如下,

while ((c = fgetc(fich)) != EOF)
{
   if (c >= 'a' && c <= 'z')
   {
       *(characters+character) = c;
       character++;
   } else if (c >= '1' && c <= '9')
   {
       *(numbers+number) = c;
       number++;
   } else if (c == '\n') 
   {
       rows++;
   }
}

此外,您需要为 numberscharacters 调用 calloc,大小至少等于 no。 numberscharacters 分别在文件中。