C 庫 - isdigit() 函式



C 的ctypeisdigit() 函式檢查傳遞的字元是否為十進位制數字字元。此函式在各種場景中很有用,例如解析使用者的數字輸入或處理需要數字驗證的資料。

十進位制數字是(數字) - 0 1 2 3 4 5 6 7 8 9。

語法

以下是 isdigit() 函式的 C 庫語法 -

int isdigit(int c);

引數

此函式接受一個引數 -

  • c - 這是要檢查的字元,作為整數傳遞。這是字元的 ASCII 值。

返回值

以下是返回值 -

  • 如果字元 c 是十進位制數字(即 '0' 到 '9'),則函式返回非零值(true)。
  • 如果字元 c 不是十進位制數字,則返回 0(false)。

示例 1:簡單的數字檢查

主函式檢查傳遞給它的數字/字元是否為數字/非數字。

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

int main() {
   char ch = '5';
   if (isdigit(ch)) {
      printf("'%c' is a digit.\n", ch);
   } else {
      printf("'%c' is not a digit.\n", ch);
   }
   return 0;
}

輸出

以上程式碼產生以下結果 -

'5' is a digit.

示例 2:字串中的數字檢查

以下程式碼演示了在處理字串和識別其中數字時使用 isdigit 的方法。

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

int main() {
   char str[] = "Hello123";
   for (int i = 0; str[i] != '\0'; i++) {
      if (isdigit(str[i])) {
         printf("'%c' is a digit.\n", str[i]);
      } else {
         printf("'%c' is not a digit.\n", str[i]);
      }
   }
   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果 -

'H' is not a digit.
'e' is not a digit.
'l' is not a digit.
'l' is not a digit.
'o' is not a digit.
'1' is a digit.
'2' is a digit.
'3' is a digit.
廣告

© . All rights reserved.