C语言实现五位数带空格输出遇else前缺}报错求助
问题原因
- 核心错误是大括号匹配错位:你的代码缩进混乱,
isdigit判断对应的if代码块没有正确闭合就直接写了else分支,编译器无法识别else对应的if,因此报错要求补}。 - 额外错误1:重复定义
number变量,函数开头已定义unsigned number,后续读取数字时又重复定义了long number。 - 额外错误2:提示文本拼写错误,
stat应为start,snprintf格式符%d和long类型的number不匹配。 - 额外错误3:
return 0放在了输入正常的分支内,其余分支没有返回值。
修复后的完整代码
#include <ctype.h> #include <stdio.h> #include <stdlib.h> int main(void) { char line[50]; printf("Give five digit number > "); if (fgets(line, 50, stdin)) { if (isdigit((unsigned char)line[0])) { char * endptr = line; long number = strtol(line, &endptr, 10); int nrOfDigitsRead = (int)(endptr - line); if (nrOfDigitsRead != 5) { printf ("Number is not five digits i.e. %d .\n", nrOfDigitsRead); } else { printf("The number you gave is: "); snprintf(line, sizeof line, "%ld", number); for( int i = 0; line[i]; i++ ) { printf(" %c", line[i]); } putchar('\n'); } } else { printf("The given number does not start with number.\n"); } } return 0; }
修复说明
- 调整了所有大括号的缩进和匹配关系,确保每一层if都有对应的闭合
},else和对应的if层级对齐,方便排查匹配问题。 - 删除了开头冗余的unsigned number定义,避免重复声明。
- 修正了snprintf的格式符为
%ld匹配long类型,修正了提示文本的拼写错误。 - 把
return 0移到了函数末尾,覆盖所有执行路径。
内容的提问来源于stack exchange,提问作者Ata
相关产品推荐
相关产品推荐

