c - 根据 int 对结构数组进行排序

标签 c arrays visual-studio sorting struct

尝试对 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);
}

最佳答案

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);

iitems 中元素的数量。

关于c - 根据 int 对结构数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405126/

相关文章:

php - Hackerrank 圆形数组旋转在 php 中未通过 100,000 次旋转测试

python - 均匀混合两个元素列表(负载平衡)

visual-studio - 在立即窗口Visual Studio中调用异步方法

c - 如何修复段错误?

c - (.文本+0xb6f): undefined reference to `src_simple'

javascript - 构建 Promise 数组不起作用,但单个 Promise 可以

visual-studio - 无法打开 Visual Studio - 引发错误 'cannot run when setup is in progress'

c# - 除了在 Visual Studio 2017 中启动之外,如何将调试器附加到其他进程?

c - 如何从 C 函数创建 shell 命令

c - Printf问题与Kernighan和Ritchie问题1-17