所以我正在开发一个程序,该程序从包含每个行/项目的“项目编号”,“单价”和“购买日期”的文件中读取行。我已经达到了可以扫描文件并以所需的图表格式组织它的程度,但我无法弄清楚如何按“项目编号”对数据进行排序。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
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稍微熟悉,但不知道如何在这里应用它。 非常感谢任何帮助,谢谢。
答案 0 :(得分:0)
好的,我相信将其分解为一些步骤会很好。
如果您不熟悉它,我强烈建议您阅读有关strtok()和qsort()函数的更多信息。
以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 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;
}
请注意,此代码仅针对您的测试用例编写。如果您的数据结构不同(如果您有三列以上等),则需要修改代码。此外,您还需要进行更多的错误处理。
这是输出:
##### 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
希望这有帮助。
巴里斯