c语言 - 通过功能验证用户输入

时间:2012-07-13 20:47:52

标签: c

我需要使用单独的函数验证用户输入。 例如,编程要求在functionA中输入,验证代码应该在FunctionB中...我知道所有ifs和while语句用于验证但我无法弄清楚如何使用两个单独的函数...这是样本运行..

#include <stdio.h>

void get_input (int * inp);
double valid_input (void);

main ()
{
    get_input (&inp);
    valid_input ();
}

void get_input (int *inp)
{
    printf("enter something");
    scanf("%d", &inp);
}

double valid_input ()
{
    // what to put here ?
}

2 个答案:

答案 0 :(得分:4)

在这种情况下,您希望将其保留在一个函数中,因为scanf返回的值确定用户输入是否有效。

另外,你不应该将参数的地址传递给scanf,它已经是一个指向int的指针。

考虑重写你的功能:

int get_input (int *inp);

// main function is here

// returns 1 if input was valid
// see documentation for scanf for possible return values
// http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
int get_input (int *inp)
{
    printf("enter something: ");
    return scanf("%d", inp); 
}

然后,您可以使用函数的返回值来确定它是否成功,如下所示:

int value;
if (get_input(&value) == 1)
{
    // input was valid
}
else
{
    // function returned an error state
}

答案 1 :(得分:1)

我不完全确定您正在寻找什么样的验证。如果您只想查看您要查找的字符类型的验证,那么Wug的回答很接近。

如果您正在寻找另一个进行某些验证的功能,这可以为您提供一个起点:

#include <stdio.h>

int get_input (int *integerINput, char *characterInput);
void valid_input (int inp);

main()
{
    int integerInput;
    char charInput[2];

    // man scanf reports that scanf returns the # of items
    //      successfully mapped and assigned.
    //      gcc 4.1.2 treats it this way.
    if (get_input (&integerInput) < 2)
    {
        printf ("Not enough characters entered.\n");
        return;
    }

    valid_input (integerInput);
}

int get_input (int *integerInput, char *characterInput)
{
    int inputCharsFound = 0;

    printf ("Enter an integer: ");

    inputCharsFound += scanf ("%d", inp);


    printf ("Enter a character: ");

    // The first scanf leaves the newline in the input buffer
    //    and it has to be accounted for here.
    inputCharsFound += scanf ("\n%c", characterInput);

    printf ("Number of characters found = %d\n", inputCharsFound);

    return inputCharsFound;
}

void valid_input (int inp)
{
    if (inp > 5)
        printf ("You entered a value greater than 5\n");
    else
        printf ("You entered a value less than 5\n");
}

修改 HasanZ在下面的评论中询问了有关如何处理多个变量的更多详细信息。我已经更新了代码以读取另一个输入字符。

我会留给您,以确定如何最好地接受相应的输入并验证输入,因为您已经用通用术语询问如何在单独的函数中进行验证。

我还会看一下here,了解有关C编程的更多信息。