簡體   English   中英

C,添加語句以檢查輸入是否為 integer

[英]C, add statement to check if input is an integer

這就是我目前所擁有的,我想在底部添加一個打印printf("Error");的語句如果輸入的數據不是數字。

int main() {
    long long number;
    long long ret;
    
    printf("Enter a number between [0 - 4294967295]: ");
    scanf("%lld", &number);
    
    printf("Number is %lld\n", number);
    //if statements to see if number is above/below the range
    if (number < 0) {
        printf("Error: This number is below the range.");
        return -1;
    }
    if (number > 4294967295) {
        printf("Error: This number is above the range.");
        return -1;
    } 
    //this is where I would like to add the statement
    return 0;
}

注意:用戶 jwdonahue 使用fgets() / sscan()指出了一個更好的解決方案


根據scanf的手冊頁:

成功時,這些函數返回成功匹配和分配的輸入項的數量 如果早期匹配失敗,這可能會小於規定的值,甚至為零。

由於您要讀取一個值,因此您首先檢索scanf()的返回值並在檢查number之前檢查它:

int read_items;
read_items = scanf("%lld", &number);
if (read_items == 0) {
  printf("Not a number\n");
  return 1; // exit with an error status (!= 0)
}

此外,您還應該在此之前檢查是否讀取了一個值,手冊頁對此進行了描述:

如果在第一次成功轉換或匹配失敗發生之前到達輸入結尾,返回EOF 如果發生讀取錯誤,也會返回 EOF

因此:

int read_items;
read_items = scanf("%lld", &number);
if (read_items == EOF) {
  printf("No value entered or error occured\n");
  return 1; // exit with an error status (!= 0)
}
if (read_items == 0) {
  printf("Not a number\n");
  return 1; // exit with an error status (!= 0)
}

  
for (i=0;i<length; i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }

isdigit(c)是 C 中的 function 可用於檢查傳遞的字符是否為數字。 如果是數字則返回非零值,否則returns 0

暫無
暫無

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

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