【发布时间】:2018-05-01 16:01:08
【问题描述】:
所以我正在开发一个程序,该程序从包含每个行/项目的“项目编号”、“单价”和“购买日期”的文件中读取行。我已经可以扫描文件并以所需的图表格式组织它,但我不知道如何按“项目编号”对数据进行排序。
这是我的代码:
#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 有点熟悉,但不知道如何在这里应用它。 非常感谢任何帮助,谢谢。
【问题讨论】:
-
您发布的所有这些代码都没有尝试解决您所描述的问题。
-
定义一个
struct数组,每个数组都包含三个适当类型的数据项。从使用fgets读取的每一行文件中提取数据。然后将qsort与自定义比较函数一起使用。 -
欢迎来到 Stack Overflow。请尽快阅读 About 和 How to Ask 页面,但更重要的是,请阅读有关如何创建 MCVE (minimal reproducible example) 的信息。要对数据进行排序,您需要存储它。这意味着您将需要多个存储字符。您遇到了问题,因为
fgetc()返回的是int,而不是char,因此您要么根本检测不到 EOF,要么在有人输入有效字符(可能是“ÿ”)时错误检测到 EOF。显示的代码并没有真正尝试解决所描述的问题;它读取一个文件并回显双标签代替逗号 - 并添加一个标题。 -
将数据存储在数组中,然后调用
qsort对其进行排序。