有没有快速检查字符串是否为数字的方法?

时间:2013-10-07 00:54:55

标签: c++

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

3 个答案:

答案 0 :(得分:1)

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

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

本主题还讨论了这个主题:How to determine if a string is a number with C++?

希望这会有所帮助:)

答案 1 :(得分:1)

#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
}

答案 2 :(得分:0)

您可以在 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 integer\n",the_number);
    }
   return 0;
  }

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

相关问题