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

C语言使用scanf校验输入恰好为6个数字,多余输入触发错误的实现方法

问题解决方案

你现有代码的问题根源是:scanf的返回值仅统计成功匹配并赋值的变量个数,不会校验输入流中是否存在超出要求的剩余内容,因此输入超过6个数字时前6个读取成功,check值为6,自然不会触发报错。

因为你尚未学习循环、仅允许使用stdio.h头文件,我们可以直接利用scanf的格式匹配特性完成多余输入校验,不需要用到循环:

修复要点

  • 修复原有代码的隐含错误:positive = positive++属于C语言未定义行为,直接写positive++即可;修正拼写错误negetive为标准拼写negative;统一所有计数逻辑的写法。
  • 新增多余输入校验:读取完6个数字后,尝试读取下一个非空白字符,若能读取成功说明存在多余输入,触发报错。

修改后完整代码

#include <stdio.h>
int main() {
    int a, b, c, d, e, f;
    int check;
    unsigned int positive = 0;
    unsigned int negative = 0;
    char tmp;
    printf("Please insert 6 numbers\n");

    check = scanf(" %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f);
    printf("%d\n", check);

    if (check != 6 ) { 
        printf("Error, please try again."); 
    } else {
        // 校验是否有多余输入
        int extra_input = scanf(" %c", &tmp);
        if (extra_input == 1) {
            printf("Error, please try again.");
            return 0;
        }
        // 正负统计逻辑
        if (a > 0) { positive++; }
        else if (a < 0) { negative++; }

        if (b > 0) { positive++; }
        else if (b < 0) { negative++; }

        if (c > 0) { positive++; }
        else if (c < 0) { negative++; }

        if (d > 0) { positive++; }
        else if (d < 0) { negative++; }

        if (e > 0) { positive++; }  
        else if (e < 0) { negative++; }

        if (f > 0) { positive++; }
        else if (f < 0) { negative++; }

        printf("There were %d positive numbers and %d negative numbers", positive, negative);
    }
    return 0;
}

校验逻辑说明

scanf(" %c", &tmp)格式串开头的空格会自动跳过输入流中所有的空白字符(包括空格、制表符、换行符),如果跳过空白后还存在有效字符,就会将该字符赋值给tmp,返回值为1,说明用户输入了超过6个的内容;如果跳过空白后已经到输入末尾,scanf返回EOF(值为-1),说明输入刚好符合要求。

内容的提问来源于stack exchange,提问作者Nati Shen-Gordon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:36:06