簡體   English   中英

C語言-通過功能驗證用戶輸入

[英]c language - Validating User Input via function

我需要使用單獨的功能來驗證用戶輸入。 例如,編程要求在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 ?
}

在這種情況下,您希望將其保留在一個函數中,因為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
}

我不能完全確定您要尋找的驗證。 如果您只是想驗證輸入的字符類型,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在下面的評論中要求提供有關如何處理多個變量的更多詳細信息。 我已經更新了代碼以讀取另一個輸入字符。

由於您已經用通用術語詢問了如何在單獨的函數中進行驗證,因此我將由您決定如何最好地接受適當的輸入並驗證該輸入。

我還將在這里查看有關C編程的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM