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

C语言程序问题求助:结果错误与fgets输入跳过问题

解决你的两个C语言程序问题

咱们逐个拆解你遇到的问题,给出具体的修复方案:

问题1:"Point Obtained"模块的Round结果不正确

看你的代码,核心问题出在**point数组的存储逻辑**上。你现在用的是一维数组int point[3];,每次循环都会覆盖这三个元素的值,最后数组里只保留了最后一轮的分数。所以当你在第二个for循环里打印所有Round的分数时,每一轮都显示的是最后一轮的数值,自然和你预期的Round 1结果不符。

修复方案:

改用二维数组存储每一轮的分数,比如int point[100][3];(这里假设最多支持100轮,你可以根据实际需求调整数组大小)。这样每一轮的分数都会被单独保存,不会被后续轮次覆盖。

修改后的关键代码片段:

// 把原来的一维数组改成二维数组
int point[100][3];

// 第一个循环:将每轮分数存入对应轮次的数组位置
for(times=1; times<=round; times++) {
    printf("## Round %d ##\n", times);
    printf("Point for player 1(%s):",name1);
    scanf("%d", &point[times-1][0]); // 数组索引从0开始,times-1对应第times轮
    printf("Point for player 2(%s):", name2);
    scanf("%d", &point[times-1][1]);
    printf("Point for player 3(%s):", name3);
    scanf("%d", &point[times-1][2]);
    total1 += point[times-1][0];
    total2 += point[times-1][1];
    total3 += point[times-1][2];
}

// 第二个循环:读取对应轮次的分数并打印
for(times=1; times<=round; times++) {
    printf("******Point obtained******\n");
    printf("## Round %d ##\n", times);
    printf("Point for player 1(%s): %d\n", name1, point[times-1][0]);
    printf("Point for player 2(%s): %d\n", name2, point[times-1][1]);
    printf("Point for player 3(%s): %d\n", name3, point[times-1][2]);
}

这样每一轮的分数都会被正确存储和展示,Round 1的结果就能符合你的预期了。

问题2:移除fflush(stdin)后fgets跳过输入的替代方案

fflush(stdin)是C标准未定义的行为(只允许对输出流使用fflush),确实不应该用。问题根源是scanf("%d", &var)读取完整数后,输入缓冲区里还残留着换行符\n,后续的fgets会直接读取这个换行符,导致看起来像是跳过了输入。

推荐的替代方案:

这里给你两种可靠的方式清空输入缓冲区的残留内容:

  1. 用循环清空缓冲区直到换行(最可靠)
    定义一个工具函数,把缓冲区里所有字符读到换行为止,确保后续输入不受影响:

    // 新增清空输入缓冲区的函数
    void clearInputBuffer() {
        int c;
        while ((c = getchar()) != '\n' && c != EOF);
    }
    

    然后在每个scanf之后调用这个函数:

    printf("How many round?:");
    scanf("%d", &round);
    clearInputBuffer(); // 清空缓冲区里的残留换行
    printf("How many player:");
    scanf("%d", &player);
    clearInputBuffer(); // 再次清空
    
  2. 用scanf格式符直接丢弃换行
    在读取整数的scanf格式串末尾加上%*c,它会读取并丢弃缓冲区里的一个字符(也就是换行符):

    printf("How many round?:");
    scanf("%d%*c", &round); // %*c 自动丢弃换行符
    printf("How many player:");
    scanf("%d%*c", &player);
    

    注意:如果用户输入整数后还输入了其他字符(比如3 abc),这种方式只会丢弃第一个字符,不如第一种方案彻底。

额外小优化:

fgets会把用户输入的换行符也读进字符串里,如果你不想名字后面带换行,可以手动去掉:

// 处理name1的换行符
name1[strcspn(name1, "\n")] = '\0';
// 同理处理name2、name3
name2[strcspn(name2, "\n")] = '\0';
name3[strcspn(name3, "\n")] = '\0';

strcspn会返回第一个\n的位置,把它替换成字符串结束符\0即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:12:52