You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言:如何读取带空格球队名称并按total值排序结构体数组?

问题解决:读取带空格的球队名称并按total值排序

1. 读取包含空格的球队名称

原代码用scanf("%s", tt.name)读取名称时,会在空格处停止,无法处理带空格的队名(如"Golden State Warriors")。解决方式是改用fgets()读取整行输入,同时处理输入缓冲区残留的换行符:

  • 读取球队数量后,消耗缓冲区里的换行符,避免fgets()直接读到空行;
  • 用fgets()读取队名后,移除字符串末尾附带的换行符(fgets()会把换行符一并读入)。

2. 按total值排序球队结构体

使用标准库的qsort()函数实现排序,需自定义比较规则(按total值降序排列,即胜场减负场的数值越大越靠前):

  • 引入<stdlib.h>头文件以使用qsort();
  • 编写compareTotal比较函数,通过返回两个球队total值的差值,指定降序排序逻辑;
  • 计算完所有球队的total值后,调用qsort()对数组进行排序。

修改后的完整代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define NAME_LENGTH 25

typedef struct {
    char name[NAME_LENGTH];
    int wins;
    int losses;
    int total;
} Total;

Total readTeamInfo(void);
void printInfo(Total tt, int);
int compareTotal(const void *a, const void *b);

int main(void) {
    int i, teams;

    printf("Number of teams > ");
    scanf("%d", &teams);
    
    // 消耗输入缓冲区中剩余的换行符
    while (getchar() != '\n');

    Total data[teams];

    for (i = 0; i < teams; i++) {
        data[i] = readTeamInfo();
        data[i].total = data[i].wins - data[i].losses;
    }

    // 按total值降序排序
    qsort(data, teams, sizeof(Total), compareTotal);

    for (i = 0; i < teams; i++) {
        printInfo(data[i], i);
    }
    return 0;
}

Total readTeamInfo(void) {
    Total tt;

    printf("Team name > ");
    fgets(tt.name, NAME_LENGTH, stdin);
    
    // 移除字符串末尾的换行符
    size_t len = strlen(tt.name);
    if (len > 0 && tt.name[len - 1] == '\n') {
        tt.name[len - 1] = '\0';
    }

    printf("Wins > ");
    scanf("%d", &tt.wins);

    printf("Losses > ");
    scanf("%d", &tt.losses);
    
    // 消耗输入缓冲区中剩余的换行符,避免影响下一次读取
    while (getchar() != '\n');

    return tt;
}

void printInfo(Total tt, int i) {
    printf("Team #%d %s: %d wins and %d losses\n", i + 1, tt.name, tt.wins, tt.losses);
}

int compareTotal(const void *a, const void *b) {
    const Total *teamA = (const Total *)a;
    const Total *teamB = (const Total *)b;
    // 降序排序:total值大的球队排在前面
    return teamB->total - teamA->total;
}

内容的提问来源于stack exchange,提问作者Arttu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 11:50:19