簡體   English   中英

使用getchar()驗證1-9之間的用戶輸入

[英]Validating user input between 1-9 using getchar()

大家好,我試圖編寫一個小程序,其中用戶必須輸入1到9之間的數字,其他任何東西都是錯誤,但是我無法驗證輸入,因為如果您輸入12,它只會讀取1且進入循環。 到目前為止,必須使用getchar()完成:

 printf(%s,"please enter a number between 1 - 9);
 int c;
 c = getchar();
    while(c != '\n') {

    int count = 1;
    count ++;

    if ((c >= '0' && c <= '9') || count > 1) {
 printf(%s, "Congrats!);
 }
 else
 {
 print(%s, "ERROR);
    }

 }

在將char轉換為int后,我也遇到了問題。如果我輸入5,我得到53。

嘗試將count> 1更改為count == 1,並將其初始化為0而不是1。這樣,您就可以保留所擁有位數的計數。 另外,請注意,因為您將count初始化為1,然后立即將其遞增,所以count> 1始終將評估為true,因此,如果您給它提供任何字符,它將始終表示它是正確的。

getchar()將返回下一個鍵入的字符。 如果您想要的不僅僅是第一個字符,您將需要在while循環中再次調用getchar()。

//Somewhere to store the result
//initialized with an invalid result value
int digitchar = 0;

//Get the first char
int c = getchar();
while (c != '\n')
{
    //Check if we already have a digit
    //and that the new char is a digit
    if (digitchar == 0 && c >= '1' && c <= '9')
    {
        digitchar = c;
    }


    //Get the next char
    c = getchar();
}

//Check if we have stored a result
if (digitchar != 0)
{
    //Success
}

請注意,如果輸入了非數字或換行符,則此操作不起作用。 您將需要將其作為錯誤以及輸入多個數字來處理。

這不適用於12,因為getchar()每次需要占用一個字符。以下示例是解決該問題的一種方法。

printf("please enter a number between 1 - 9");
int c[10], count=1;
//Declare an array because user may insert a bigger number
char number;
//This loop allow the user to enter an input
for(i=0;i<10;i++){
    number = getchar();
    if (number != ' '){
        c[i] = atoi(number);
        sum = sum + c[i];
    }
    else if(number == ' '){
        //Terminate the loop when user stop typing
        break;
    }
    else if( sum > 9 || sum < 0){
        //Start loop again until user enter valid input
        printf("You entered a number out of field try again\n");
        continue;
    }

}
while(c != '\n') {

        count ++;

    if ((c >= '0' && c <= '9') || count > 1) {
        printf("%d Congrats!",c);
    }
    else
    {
        printf(" %d ERROR", c);
    }

}

請記住,getchar()返回char的ascii值,因此,當您將值傳遞給函數時,必須減去char'0'才能將實際的十進制值傳遞給函數。 還有一點是,您必須清除輸入緩沖區。 如果用戶輸入了錯誤的輸入,則在再次嘗試讀取輸入之前,必須確保輸入緩沖區中沒有剩余任何內容。 希望這可以幫助。

int main(void) {

    int input = 0; // 0 is the sentinel value to close program   

    printf("\n%s\n", "Enter value between 1-9 .\nEnter [0] to finish.");

    do {
        input = getchar();

        if (((input>= '1') && (input <= '9') || input == '0') && getchar() == '\n') {

            if ((input >= '1') && (input <= '9')) {
                callYourOwnFuntionAndPassValue(input - '0');
                printf("\n%s\n", "Enter value between 1-9 .\nEnter [0] to finish.");
            }
        } 
        else {
            while (getchar() != '\n') {} // clear input buffer
            printf("\n%s\n", "Please enter a valid number");
        }

    } while (input != END_PROGRAM);


    return NO_ERROR; // NO_ERROR  = 0
}

暫無
暫無

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

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