【发布时间】:2014-03-01 20:20:33
【问题描述】:
当验证来自用户的输入并通过 C 编程中的函数进行验证时,您是否会有很多 if 语句检查从验证函数返回的 1 或 0?
如果你不明白我的意思,那么下面是我严格输入的代码作为示例。它绝对不会在其他任何地方使用。
#include <stdio.h>
int checkIfZero(int x){
int result = 1;
if (x ==0){
printf ("You typed in zero for your age. Try again.\n\n");
result = 0;
}
return result;
}
int checkUpper(char x){
int result = 1;
if (x > 96){
printf("Iniitial is not a uppercase. Try again\n\n");
result =0;
}
return result;
}
int main(int argc, const char * argv[])
{
int age;
char initial;
int correct = 0;
do {
int counter; // holds returned result of first function
int counter2; // holds returned result of the second function
printf("Please type your age and the initial of your first name in Uppercase\n");
scanf("%d %c", &age, &initial);
counter = checkIfZero(age);
if(!counter){
continue;
}
counter2 = checkUpper(initial);
if (!counter2){
continue;
}
correct = 1;
printf("Correct\n");
} while (correct==0);
return 0;
}
如果您注意到,我有 2 个验证输入的函数。稍后,我必须创建不同的变量,这些变量将具有 1 或 0 形式,这些函数返回并使用 if 语句检查它们。
现在假设我创建了大约 10 个验证函数
这是否意味着我必须创建 10 个不同的变量来捕获函数的返回结果,然后键入 10 个 if 语句?
如果人们通常这样做,我可以接受,但情况是这样吗?
【问题讨论】:
标签: c function validation if-statement