21xrx.com
2025-07-11 10:40:58 Friday
登录
文章检索 我的文章 写文章
C++中的isdigit()函数用法及示例
2023-06-29 00:04:28 深夜i     19     0
C++ isdigit() 函数 用法 示例

C++中的isdigit()函数是一个非常常用的函数,它可以用来判断一个字符是否为数字。如果是数字,则返回非零值;否则返回0。isdigit()函数位于头文件 中,以下是isdigit()函数的声明:

int isdigit(int c);

参数c是一个整数值,它代表待判断的字符。

下面通过一些示例来演示isdigit()函数的用法:

1. 判断给定字符是否是数字

#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
  char c = '5';
  if (isdigit(c))
    cout << c << " is a digit" << endl;
   else
    cout << c << " is not a digit" << endl;
  
  c = 'a';
  if (isdigit(c))
    cout << c << " is a digit" << endl;
   else
    cout << c << " is not a digit" << endl;
  
  return 0;
}

上述代码的输出结果:

5 is a digit
a is not a digit

2. 判断字符串中的字符是否都是数字

#include <iostream>
#include <ctype.h>
#include <cstring>
using namespace std;
bool isAllDigits(char *str) {
  int len = strlen(str);
  for (int i = 0; i < len; i++) {
    if (!isdigit(str[i]))
      return false;
    
  }
  return true;
}
int main()
{
  char *str = "123456";
  if (isAllDigits(str))
    cout << str << " consists of all digits" << endl;
   else
    cout << str << " contains non-digit characters" << endl;
  
  str = "abc123";
  if (isAllDigits(str))
    cout << str << " consists of all digits" << endl;
   else
    cout << str << " contains non-digit characters" << endl;
  
  return 0;
}

上述代码的输出结果:

123456 consists of all digits
abc123 contains non-digit characters

正如以上两个示例所示,isdigit()函数可以在C++中方便地用来判断一个字符或一组字符是否为数字。在实际编程中,我们可以通过该函数实现很多有趣的功能。

  
  

评论区