c - 对矩阵进行冒泡排序以按升序获取一些字符
问题描述
我有一个名为的文件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
使用您在问题末尾看到的代码,我将字符分成两个列表,命名如下:numbers
这样characters
我就可以在屏幕上按如下方式打印它们(第一个是数字,然后是字母):
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;
}
解决方案
您已经在用于读取文件的循环内进行了交换number
和character
计数器。while
更改如下,
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++;
}
}
此外,您需要调用calloc
并且大小至少等于 no。的和分别在文件中。numbers
characters
numbers
characters
推荐阅读
- graphql - Apollo graphql:makeExecutableSchema 和游乐场
- c# - 有时 IOrganizationService 对象为空
- javascript - 如何对 observable 上的数据数组进行排序?
- data-science - 预测时如何考虑特征?
- linphone - linphonecsh - 何时调用退出?
- opencl - 为什么这个简单的 OpenCL 代码没有向量化?
- ios - 在 Hour 和 Minute 之间添加冒号 (:) 并在 UIDatePicker 中禁用默认 AM/PM
- google-sheets - 是否可以在不使用脚本的情况下使用另一个单元格(甚至更好的行)被修改的日期来更新一个单元格?
- python - CDK 无法创建 CloudWatch Logs SubscriptionFilter
- windows - 设置受保护的文件夹,例如通过注册表操作