对包含从C中的文件输入的数字的字符串进行排序?

所以我正在研究一个程序,该程序从包含每个行/项目的“项目编号”,“单价”和“购买日期”的文件中读取行。 我已经达到了可以扫描文件并以所需的图表格式组织它的程度,但我无法弄清楚如何按“项目编号”对数据进行排序。

这是我的代码:

#include  #include  int main() { FILE *fp; char ch; fp = fopen("f.txt", "r"); //open the file named f.txt if (fp == NULL) //In case we can't find the file, notify the user printf("File not found\n"); printf("Item \t\tUnit Price\tPurchase Date\n"); //set up the header while ((ch = fgetc(fp)) != EOF) { //set the character equal to the character next in the file using fgetc, and //if its not equal to the end of file if (ch == ',') { printf("\t\t"); //add two tabs every time a ',' is encountered. } else { printf("%c",ch); //just display the output from the file } } fclose(fp); //closes the file return 0; } 

样本输入

在此处输入图像描述

样本输出

在此处输入图像描述

请参阅,我需要按项目编号(最左边的列)对输出进行排序。 我的想法是将每一行添加到字符串数组(c中的char数组),然后从那里我不知道如何识别项目编号,以便为输出排序。 我对fscanf稍微熟悉,但不知道如何在这里应用它。 非常感谢任何帮助,谢谢。

好吧,我相信把它分解成一些步骤会更好。

  1. 定义特定于您的数据的结构
  2. 逐行读取文件
  3. 对于每一行,使用strtok()来拆分字符串
  4. 将这些值添加到struct数组中
  5. 使用qsort()对struct数组进行排序

我强烈建议您阅读有关strtok()和qsort()函数的更多信息,如果您不熟悉它们的话。

这是代码:

 #include  #include  #include  // STEP 1 typedef struct { int item; float price; char date[50]; } Data; int compare (const void * a, const void * b) { Data *dataA = (Data *)a; Data *dataB = (Data *)b; return ( dataA->item - dataB->item ); // Ascending order //return ( dataB->item - dataA->item ); // Descending order } int main() { FILE * fp; char line[150]; Data data[3]; int i = 0; fp = fopen("f.txt", "r"); while (1) { // STEP 2 if (fgets(line,150, fp) == NULL) break; // STEP 3-4 char * pch; pch = strtok (line,","); data[i].item = atoi(pch); // item part pch = strtok (NULL, ","); data[i].price = atof(pch); // unit price part pch = strtok (NULL, ","); strcpy(data[i].date, pch); // purchase date part i++; } printf("##### BEFORE #####\n"); printf("Item \t\tUnit Price\tPurchase Date\n"); //set up the header for (int k = 0; k < 3; k++) { printf("%d\t\t%f\t%s", data[k].item, data[k].price, data[k].date); } // STEP 5 qsort (data, 3, sizeof(Data), compare); printf("\n##### AFTER #####\n"); printf("Item \t\tUnit Price\tPurchase Date\n"); //set up the header for (int k = 0; k < 3; k++) { printf("%d\t\t%f\t%s", data[k].item, data[k].price, data[k].date); } fclose(fp); return 0; } 

请注意,此代码仅针对您的测试用例编写。 如果您的数据结构不同(如果您有三列以上等),则需要修改代码。 此外,您还需要做一些error handling。

这是输出:

 ##### BEFORE ##### Item Unit Price Purchase Date 583 13.500000 10/24/2005 3912 599.989990 7/27/2008 12 19.990000 3/16/2001 ##### AFTER ##### Item Unit Price Purchase Date 12 19.990000 3/16/2001 583 13.500000 10/24/2005 3912 599.989990 7/27/2008 

希望这可以帮助。

巴里斯