代码之家  ›  专栏  ›  技术社区  ›  Wajih Benzayed

如何使用内置库检查字符串是否为数字?

  •  0
  • Wajih Benzayed  · 技术社区  · 1 年前

    我尝试使用isdigit函数,但它只适用于字符。我知道我可以编写一个函数来检查字符串中的每个字符,但c中已经内置了这种方法吗

    #include <cs50.h>
    #include <ctype.h>
    #include <stdio.h>
    
    int main(int argc, string argv[])
    {
        if (argc != 2)
        {
            printf("Usage: ./caesar key");
            return 1;
        }
        else if (isdigit(argv[1]) != 1)
        {
            printf("Usage: ./caesar key");
            return 1;
        }
    }
    
    
    1 回复  |  直到 1 年前
        1
  •  0
  •   chqrlie    1 年前

    您不能使用 isdigit() 按照您在问题中的方式:它的参数必须是一个字符(所有类型的值 unsigned char )或特殊负值 EOF 。传递字符串具有未定义的行为。

    你的问题有很多可能的答案,这取决于你的意思 如果字符串是数字 :

    • 检查指针是否指向字符串 s 仅由数字组成 strspn 定义于 <string.h> :

      if (*s && s[strspn(s, "0123456789")] == '\0') {
          // s is not empty and only contains digits
      }
      
    • 检查它是否表示一个十进制整数,是否包含可选的租赁空格和可选的符号:

      char *p;
      strtol(s, &p, 10);
      if (p != s && *p == '\0') {
          // s contains the decimal representation of an integer
      }
      

    以下是使用 isdigit 正确地:

    #include <cs50.h>
    #include <ctype.h>
    #include <stdbool.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    bool string_is_number(const char *s) {
        // reject empty string
        if (*s == '\0') {
            return false;
        }
        // skip digits
        while (isdigit((unsigned char)*s)) {
            s++;
        }
        // return true if all characters are digits
        return *s == '\0';
    }
    
    int main(int argc, char *argv[]) {
        if (argc != 2) {
            printf("Usage: ./caesar key\n");
            return 1;
        }
        if (!string_is_number(argv[1])) {
            printf("Usage: ./caesar key\n");
            printf("   key must be a number\n");
            return 1;
        }
        int key = strtol(argv[1], NULL, 10);
        //...
    }