有没有一种快速的方法来检查字符串是否是数字

Is there a quick way to check if a string is numeric?

本文关键字:方法 检查 字符串 数字 是否是 一种 有没有      更新时间:2023-10-16

是否可以检查字符串变量是否完全是数字变量?我知道您可以遍历字母表以检查非数字字符,但是还有其他方法吗?

我能想到的最快的方法是尝试用"strtol"或类似的函数来转换它,看看它是否可以转换整个字符串:

char* numberString = "100";
char* endptr;
long number = strtol(numberString, &endptr, 10);
if (*endptr) {
    // Cast failed
} else {
    // Cast succeeded
}

此线程中还讨论了本主题:如何确定字符串是否是带C++的数字?

希望这对:)有所帮助

#include <iostream>
#include <string>
#include <locale>
#include <algorithm>
bool is_numeric(std::string str, std::locale loc = std::locale())
{
    return std::all_of(str.begin(), str.end(), std::isdigit);
}
int main()
{
    std::string str;
    std::cin >> str;
    std::cout << std::boolalpha << is_numeric(str); // true
}

您可以在 ctype 库中使用 isdigit 函数:

  #include <stdio.h>
  #include <stdlib.h>
  #include <ctype.h>
  int main ()
  {
    char mystr[]="56203";
    int the_number;
    if (isdigit(mystr[0]))
    {
      the_number = atoi (mystr);
      printf ("The following is an integern",the_number);
    }
   return 0;
  }

本示例仅检查第一个字符。 如果你想检查整个字符串,那么你可以使用循环,或者如果它是一个固定的长度和小的,只需将isdigit()与&&结合起来。