我需要使用一个单独的函数来验证用户输入。例如,编程要求输入的是functionA,而验证代码应该是FunctionB……我知道所有用于验证的if和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 ?
}发布于 2012-07-14 05:12:43
我不能完全确定您正在寻找的验证是什么。如果您只是想验证您要查找的字符类型是否已输入,那么Wug的答案是close。
如果您正在寻找另一个执行一些验证的函数,这可以为您提供一个起点:
#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");
}EDIT HasanZ在下面的评论中询问了有关如何处理多个变量的更多详细信息。我已经更新了代码以读入另一个输入字符。
我将留给您来决定如何最好地接受适当的输入并验证该输入,因为您已经泛泛地询问了如何在单独的函数中进行验证。
我也会看看here,以获得更多关于C编程的信息。
发布于 2012-07-14 04:57:42
在这种情况下,您可能希望将其保存在一个函数中,因为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
}https://stackoverflow.com/questions/11478132
复制相似问题