【问题标题】:How to connect a string with the appropriate integer after sorting?排序后如何将字符串与适当的整数连接起来?
【发布时间】:2021-06-08 19:10:51
【问题描述】:

有人可以帮我解决 C 语言中的这个问题吗?我需要按字母顺序对排行榜进行排序,并且按分数排序。我使用atoi() 将字符串转换为整数,但名称保持在它们留下的顺序。这是排序的函数:

void bubbleSort2(int arr[], int n)
{
    int c,d;
    int swap;
    for (c = 0; c < n - 1; c++)
    {
        for (d = 0; d < n - c - 1; d++)
        {
            if (arr[d] < arr[d + 1])
            {
                swap = arr[d];
                arr[d] = arr[d + 1];
                arr[d + 1] = swap;
            }
        }
    }
}

void sortScores() {
    FILE* fp = openFile();
    int x[128];
    char line[128][20];
    int i = 0, j = 0;
    int tot = 0;
    while (fgets(line[i], 20, fp))
    {
        line[i][strlen(line[i]) - 1] = '\0';
        i++;
    }
    tot = i;
    for (int i = 0; i < tot; i++)
    {   
        char* sep = strchr(line[i], ' ');
        *sep = '\0';
        x[i] = atoi(sep + 1);
    }
    bubbleSort2(x, tot);
    printf("Sorted by scores:\n");
    for (int i = 0; i < tot; i++)
    {
        printf("%s %d\n", line[i],x[i]);
    }
    fclose(fp);
}

这是输出:

Sorted alphabetical:
Branimir 100
Branimir 700
Brekalo 100
Hrvoje 350
Ilija 0
Ilija 50
Marin 100
Marin 400
Marko 0
Marko 300
Matej 0
Matej 900
Nikola 0
Pero 100
Pero 150
Ramal 100
Simun 550
Skoric 0

Sorted by scores:
Ramal 900
Ilija 700
Ilija 550
Pero 400
Pero 350
Nikola 300
Marko 150
Marin 100
Marko 100
Marin 100
Matej 100
Branimir 100
Matej 50
Branimir 0
Brekalo 0
Skoric 0
Hrvoje 0
Simun 0

Matej 应该排在第一位,而不是 Ramal。我希望你能帮我解决这个问题。

【问题讨论】:

  • 将名称和分数放入struct,然后按分数对structs 进行排序。

标签: c string integer atoi strchr


【解决方案1】:

您只是在排序值而不是名称。

同时在排序函数中更改char line[128][20]的索引。

在主函数中传递bubbleSort2(x, tot,line);

冒泡排序

void bubbleSort2(int arr[], int n,char line[128][20])
{
    int c,d;
    int swap;
    for (c = 0; c < n - 1; c++)
    {
        for (d = 0; d < n - c - 1; d++)
        {
            if (arr[d] < arr[d + 1])
            {
                swap = arr[d];
                arr[d] = arr[d + 1];
                arr[d + 1] = swap;
                swap(line[d],line[d+1]);
            }
        }
    }
}

希望对你有帮助:)

【讨论】:

    【解决方案2】:

    你需要使用结构来存储你的数据。

    #define MAXNAME 20
    
    typedef struct
    {
        int score;
        char name[MAXNAME];
    }student;
    
    void bubbleSort2(student arr[], size_t n)
    {
        /* ..... */
        if (arr[d].score < arr[d + 1].score)
    
        /* etc etc */
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 2023-01-24
      • 2013-10-20
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多