我在试图排序int
号时遇到了麻烦。我正在尝试根据它的数字(nummer)显示项目。 int main
和#includes
在程序中,无法复制它们。是否有一个优先处理这个问题的原因,有人可以解释一下,我已经尝试了一段时间了哈哈。感谢
char *oneline, *tok;
char envara[512];
char delim[] = ",";
FILE *fp;
int i;
struct vara
{
int nummer;
char namn[100];
float pris;
float volym;
char typ[100];
char stil[100];
char forpackning[20];
char land[20];
char producent[50];
float alkoholhalt;
} items[100];
if ((fp = fopen("varor.csv", "r")) == NULL)
{
fprintf(stderr, "Filen varor.csv gick inte att öppna\n");
exit(-1);
}
for (i = 0; i < 100 && fgets(envara, 512, fp); i++)
{
envara[strlen(envara) - 1] = '\0';
oneline = strdup(envara);
tok = strtok(oneline, delim);
items[i].nummer = atoi(tok);
tok = strtok(NULL, delim);
strncpy(items[i].namn, tok, (max(strlen(tok), sizeof(items[0].namn))));
tok = strtok(NULL, delim);
items[i].pris = atof(tok);
tok = strtok(NULL, delim);
items[i].volym = atof(tok);
tok = strtok(NULL, delim);
strncpy(items[i].typ, tok, strlen(tok));
tok = strtok(NULL, delim);
strncpy(items[i].stil, tok, strlen(tok));
tok = strtok(NULL, delim);
strncpy(items[i].forpackning, tok, strlen(tok));
tok = strtok(NULL, delim);
strncpy(items[i].land, tok, min(strlen(tok), sizeof(items->land)));
tok = strtok(NULL, delim);
strncpy(items[i].producent, tok, strlen(tok));
tok = strtok(NULL, delim);
items[i].alkoholhalt = atof(tok);
printf("nummer: %d\n"
"namn: %s\n"
"pris: %f\n"
"volym: %f\n"
"typ: %s\n"
"stil: %s\n"
"forpackning: %s\n"
"land: %s\n"
"producent: %s\n"
"alkoholhalt: %f\n\n",
items[i].nummer,
items[i].namn,
items[i].pris,
items[i].volym,
items[i].typ,
items[i].stil,
items[i].forpackning,
items[i].land,
items[i].producent,
items[i].alkoholhalt
);
free(oneline);
}
fclose(fp);
}
答案 0 :(得分:1)
int cmpVara(const struct vara *left, const struct vara *right)
{
// quick & dirty way to compare two ints.
return (long) left.nummer - (long) right.nummer;
}
// :
// :
qsort(items, i, sizeof(vara), cmpVara);
i
是items
中的元素数量。