如何修复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
相关产品推荐
相关产品推荐

