C 编程中验证输入的常规编码

标签 c function validation if-statement

当验证用户的输入并通过 C 编程中的函数执行此操作时,您是否会使用很多 if 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;
}

如果你注意到的话,我有两个函数来验证输入。稍后,我必须创建不同的变量,这些变量要么具有 1 要么 0 形式这些函数返回的值,并使用 if 语句检查它们。

现在假设我创建了 10 个左右的验证函数

这是否意味着我必须创建 10 个不同的变量来捕获函数的返回结果,然后键入 10 个 if 语句?

如果人们通常都是这么做的,我可以接受,但事实真的是这样吗?

最佳答案

您不必将结果放入变量中:

counter = checkIfZero(numSiblings);
if(!counter){
  continue;

可以成为:

if (!checkIfZero(numSiblings))
  continue;

关于C 编程中验证输入的常规编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22119843/

相关文章:

java - 使用约束注释验证 json 不起作用

php - Laravel 字符串验证以允许空字符串

c - 我应该如何防止硬链接(hard link)攻击?

strnlen可以用memchr实现吗?

c - 在不按 "enter"的情况下获取 c 中的字符

C11 - 通用选择中的枚举

javascript - 在javascript中需要帮助包装函数并正确处理 "this"

javascript - Javascript 中的函数名称(e)

Python:默认参数值与全局变量

html - 使用 select2 时保留输入验证 CSS 类