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

如何修复C语言代码中的类型冲突及isdigit相关错误?

修复C程序中的类型冲突与错误

错误原因与修复方案

1. 未定义的bool类型

  • 问题:sub.h中使用了bool类型,但未包含<stdbool.h>头文件,导致编译器无法识别该类型。
  • 修复:在sub.h开头添加#include <stdbool.h>,确保所有包含该头文件的代码都能正确识别布尔类型。

2. 与标准库函数重名冲突

  • 问题:C标准库的<ctype.h>中已存在isdigit函数,原型为int isdigit(int c),你自定义的bool isdigit(char c)与其重名且类型不匹配,触发编译冲突。
  • 修复:将自定义的isdigit函数重命名(例如is_digit),同步更新头文件声明和所有调用处的函数名。

3. 代码优化建议

  • 原循环固定遍历N次,可改为遍历到字符串结束符'\0',避免无效循环;
  • 判断字符是否为数字的循环可简化为直接范围判断,提升效率。

修改后的完整代码

main.c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include "sub.h"

#define N 120

int main (void){
    char eingabe[N+1]={0};
    int zahlen[10]={0};

    fgets(eingabe,N,stdin);

    for(int i=0; eingabe[i] != '\0'; i++){
        if(is_digit(eingabe[i]))
        {
            int zahl = toNumber(eingabe[i]);
            zahlen[zahl]++;
        }
    }

    for (int j=0; j<10; j++)
    {
        printf("%d: %d \n",j, zahlen[j]);
    }
    return 0;
}

sub.h

#include <stdbool.h>

bool is_digit(char c);
int toNumber(char c);

sub.c

#include "sub.h"

bool is_digit(char c){
    return (c >= '0' && c <= '9');
}

int toNumber (char c){
    return c - '0';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:57:38