簡體   English   中英

C確定用戶輸入是否為整數

[英]C Determine if user input is an integer

嗨,我需要提示用戶一些輸入,然后對其進行驗證。 只有在輸入為正整數且不大於23的情況下,才必須驗證輸入。我遇到的唯一問題是,當用戶輸入非數字輸入(如“ hello”)時。 下面的代碼無法成功檢測到任何輸入都是非數字的,盡管我嘗試了許多方法來執行此操作,但它們似乎都無法正常工作。 下面是我似乎通過將輸入作為字符串然后將其轉換為整數而得到的最接近的數字,但是它仍然不起作用。 任何幫助,將不勝感激。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>


int main(void) {
    int height;
    char input[50];
    int cont = 0;
    while (cont == 0) {
        printf("Please provide a non-negative integer no greater than 23.\n");
        scanf("%s", &input);
        height = atoi(input);
        if (height <= 23 && height >= 0) {
            cont = 1;
        } else {
            //do nothing
        }
    }
    printf("Valid Input.\n");
    return 0;
    }

atoi()函數沒有提供返回錯誤指示符的條件。 相反,您可以使用strtol()函數:

char *end;
height = strtol(input, &end, 10);
if (end == input) {
    // no digits were entered
    puts("Invalid input.");
    continue;
}
#include <stdio.h>

int main(void) {
    int height;

    while(1){
        printf("Please provide a non-negative integer no greater than 23.\n");
        //if(2==scanf("%d%c", &height, &nl) && nl == '\n' && 0<= height && height <= 23)//more limited for "number\n"
        if(1==scanf("%d", &height) && 0<= height && height <= 23)
            break;
        //Clear of invalid input
        while(getchar()!='\n')
            ;
    }
    printf("Valid Input(%d).\n", height);
    return 0;
}

我假設您必須將整個輸入考慮在內,而不是僅將某些部分(例如“ 12jjj”和“ 23h”)視為無效。

在我看來,由於23僅為2個字符,因此檢查字符串的長度和各個字符沒有什么害處。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

bool ValidateInput (char * input, int &output)
{
    if (strlen(input) > 2)
        return false;

    for (int index = 0; index < strlen (input); index++)
    {
        if ((input[index] < '0') || input[index] > '9')
            return false;
    }

    output = atoi(input);

    return true;

}


int main(void) {
    int height;
    char input[50];
    int cont = 0;
    while (cont == 0) {
        printf("Please provide a non-negative integer no greater than 23.\n");
        scanf("%s", input);

        if (ValidateInput (input, height))
            break;
    }
    printf("Valid Input.\n");
    return 0;
    }

我希望這有幫助。

暫無
暫無

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

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