有没有一种快速的方法来检查字符串是否是数字
Is there a quick way to check if a string is numeric?
是否可以检查字符串变量是否完全是数字变量?我知道您可以遍历字母表以检查非数字字符,但是还有其他方法吗?
我能想到的最快的方法是尝试用"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()与&&结合起来。
相关文章:
- C++:正在检查LinkedList中的回文-递归方法-错误
- 检查哪个对象调用了另一个对象的对象方法
- 检查两个节点在子节点上是否具有相同状态的更优雅的方法
- 检查类是否在方法中实例化
- 检查类方法中是否(此 == nullptr)
- 检查子类型时的专用方法模板
- 检查两个向量是否并行的最有效方法
- 如何检查在编译时是否调用了模板化方法?
- 尝试编译SFINAE检查中使用的方法体时发生编译错误
- 有没有一种简单的方法来检查C++中的不安全表达式
- 是否有更有效的方法来检查元素是否在给定的区间内
- 检查特定目录中是否存在与文件匹配的 abc* 的最佳方法
- 检查数组是否等于的最快方法?
- 替换枚举以最大化编译时间检查的最佳方法
- 双重检查创建单例问题的方法
- 如果方法不进行类型检查,为什么C++模板匹配?
- C++:检查向量中的元素是否大于另一个具有相同索引的元素的有效方法?
- 检查子类是否执行了方法重写
- 最快/最小方法检查字符串是否包含多个单词
- SFINAE c++方法检查