【发布时间】:2018-08-26 15:53:50
【问题描述】:
我发现了这个练习,我必须创建一个数据结构,读取一些输入,将输入存储在“适当的”数据结构中,然后将所有内容打印到一个文本文件中。
我期待添加一个按星级排序酒店列表的功能,所以如果一家酒店有 5 星,它将在列表的顶部。有可能这样做吗?我可以用数组做到这一点吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct inputs {
char nome[30];
char via[30];
char stars[30];
int num;
};
int main(void)
{
struct inputs inputs = {"", "", ""};
FILE *cfPtr; // cfPtr = clients.txt file pointer
// fopen opens file. Exit program if unable to create file
if ((cfPtr = fopen("clients.txt", "w")) == NULL) {
puts("File could not be opened");
}
else {
puts("Enter the account, name, and balance.");
puts("Enter EOF to end input.");
printf("%s", "? ");
//scanf("%[^\n]s%[^\n]s%[^\n]s", inputs.via, inputs.nome, inputs.stars);
fgets(inputs.nome, 30, stdin);
inputs.nome[strcspn(inputs.nome,"\n")] = '\0';
fgets(inputs.via, 30, stdin);
inputs.via[strcspn(inputs.via,"\n")] = '\0';
fgets(inputs.stars, 30, stdin);
inputs.stars[strcspn(inputs.stars,"\n")] = '\0';
inputs.num = strlen(inputs.stars);
//printf("%s%s%s", inputs.nome, inputs.via, inputs.stars);
// write account, name and balance into file with fprintf
while (!feof(stdin)) {
fprintf(cfPtr, "%s; %s; %s; %d\n", inputs.nome, inputs.via, inputs.stars, inputs.num);
/*scanf("%[^\n]s", inputs.via);
scanf("%[^\n]s", inputs.nome);
scanf("%[^\n]s", inputs.stars);*/
fgets(inputs.nome, 30, stdin);
inputs.nome[strcspn(inputs.nome,"\n")] = '\0';
fgets(inputs.via, 30, stdin);
inputs.via[strcspn(inputs.via,"\n")] = '\0';
fgets(inputs.stars, 30, stdin);
inputs.stars[strcspn(inputs.stars,"\n")] = '\0';
inputs.num = strlen(inputs.stars);
}
fclose(cfPtr); // fclose closes file
}
}
【问题讨论】:
-
您可能想了解the
qsortfunction。 -
我对 qsrot 不是很熟悉,我可能希望用冒泡排序算法来做,是的,我正在尽快删除 !feof
-
只需使用
int8_t 而不是char stars[30];。 -
两者有什么区别? @kiranBiradar
标签: c arrays data-structures file-handling