【发布时间】:2018-08-27 14:18:18
【问题描述】:
#include <stdio.h>
#include <string.h>
#define SIZE 200
void check(char str[]);
void check(char str[]){
/* checking if the characters entered are digits */
int i;
int j=0;
char tel[10];
for(i = 0; str[i] != '\0'; i++){
if(str[i] >= '0' && str[i] <= '9'){
tel[j++] = str[i];
}
}
tel[j] = '\0';
/* checking if length of zip code is less than 5 digits */
if(strlen(tel) < 5)
printf("Not enough digits on input!");
/* if length of zip code is 5 digits */
else if (strlen(tel) == 5){
printf("\nProgram Output: ");
printf("(");
/* formating zip code with parenthesis around zip */
for(i = 0; tel[i] != '\0' && i < 5; i++){
printf("%c", tel[i]);
}
printf(")");
};
}
int main(){
/* variable declaration */
char str[SIZE];
printf("Enter a zip code: ");
scanf("%s", str);
check(str);
return 0;
}
我正在编写一个简单的 C 代码,用于验证来自用户的 5 个字符的邮政编码字符串。如果少于 5 个字符,程序输出错误信息。如果正好是 5 个字符,请在邮政编码周围加上括号。
当我测试我的代码时,只有我的错误消息有效。当我输入 5 个字符时,我的“else if”参数没有被执行。这是我将 char 输入传递给我的函数的方式吗?
【问题讨论】:
-
它对我有用.. 有什么问题?
-
注意
check()中第二个for循环的}后面的分号是多余的;它标志着一个空语句的结束。 (另外,check()不是一个好的函数名称;它可能应该是check_zip()或类似名称) -
确保消息以换行符结尾也是一个好主意,以便及时显示输出。当您在输入前进行提示时,换行符不是一个好主意,但使用
fflush(stdout)可确保写入待处理的数据。无论如何,它可能会出现——通常情况下,标准 I/O 库会在从标准输入读取数据之前将挂起的输出刷新到标准输出,如果两者都连接到终端的话——但使用fflush(stdout)可以确保。 -
抱怨:在我编辑代码之前的不稳定缩进意味着我错误地识别了
};所属的语句 - 它位于else if语句的末尾,而不是for循环的末尾,而是它仍然是 100% 多余的(尽管在这种情况下大多是无害的)。
标签: c function if-statement