【发布时间】:2017-04-29 06:31:42
【问题描述】:
这是用 C 语言编写的,我正在尝试使用函数和指向存储状态的数组的指针对文本文件中 2015 年人口中的数据进行升序排序。我想尝试使用交换此函数内的算法。
如何使用我的 ascensionOrder 函数对 2015 年人口中的数据进行排序,然后按升序输出?
这是我的代码:`
#include <stdio.h>
#define FILENAME "PopulationData.txt"
int main(void)
{
void acensionOrder(int *populationData);
void replace(char*s, char a, char b);
char header[3][30];
char state[51][32];
int census[51][2];
FILE *myfile;
myfile = fopen(FILENAME,"r");
int x;
if (myfile== NULL)
{
printf("Errror opening file. \n");
}
else
{
fscanf(myfile, "%s%s%s", header[0], header[1], header[2]);
for (x = 0; x < 51; x++)
{
//fscanf(myfile, "%31s%d%d", state[x], &census[x][0], &census[x][1]); //testing
fscanf(myfile, "%*2c%s %d %d", state[x], &census[x][0], &census[x][1]); //Stores the text in the data file into array
replace(state[x], '_', ' '); //Replaces the lines
replace(state[x], '.', ' '); //Replaces the periods
//printf("%s\t%d\t%d\n", state[x], census[x][0], census[x][1]);
//printf("%2d %31s %10d %10d\n", x, state[x], census[x][0], census[x][1]); //Testing of sort
}
}
acensionOrder(&census[x][1]);
fclose(myfile);
//getchar();
//getchar();
return 0;
}
void acensionOrder(int *populationData) //This function sorts the 2015 data into ascending order
{
int j,k,m;
int sorted2015;
for(k=0; k<m; k++)
{
//m=k;
for(j=0; j<(m-1); j++)
{
if(*(populationData+j)<*(populationData+m))
//m=j;
sorted2015=*(populationData+m);
*(populationData+m)=*(populationData+k);
*(populationData+k)=sorted2015;
}
}
printf("%d\n", sorted2015);
}
void replace(char*s, char a, char b) //This function uses pointers to find characters
{
for(;*s; s++)
{
if(*s==a)*s = b;
}
}
`
这是程序读取的文本文件: Text file for US population
【问题讨论】:
-
“如何使用我的 ascensionOrder 函数对数据进行排序”。调用函数?如果您说该功能不起作用,请描述具体行为。
-
你以前用过
qsort吗?我还建议将您的数据存储在某种struct中。 -
如果您发布您的文本文件并正确格式化它也会更容易。它与间距不一致,坦率地说很难阅读。
-
@RoadRunner 间距似乎与制表符一致。
-
m未在int j,k,m; ...for(k=0; k<m; k++)中初始化
标签: c arrays file sorting text