问题描述
我在尝试编写一个检查字符串是否为数字的函数时遇到了很多麻烦.对于我正在编写的游戏,我只需要检查我正在读取的文件中的一行是否是数字(我会知道它是否是这样的参数).我编写了以下函数,我认为它运行顺利(或者我不小心编辑以停止它,或者我精神分裂症或 Windows 精神分裂症):
I've had quite a bit of trouble trying to write a function that checks if a string is a number. For a game I am writing I just need to check if a line from the file I am reading is a number or not (I will know if it is a parameter this way). I wrote the below function which I believe was working smoothly (or I accidentally edited to stop it or I'm schizophrenic or Windows is schizophrenic):
bool isParam (string line)
{
if (isdigit(atoi(line.c_str())))
return true;
return false;
}
推荐答案
最有效的方法是遍历字符串,直到找到一个非数字字符.如果有非数字字符,可以认为字符串不是数字.
The most efficient way would be just to iterate over the string until you find a non-digit character. If there are any non-digit characters, you can consider the string not a number.
bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
或者如果你想用 C++11 的方式来做:
Or if you want to do it the C++11 way:
bool is_number(const std::string& s)
{
return !s.empty() && std::find_if(s.begin(),
s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end();
}
正如下面评论中所指出的,这仅适用于正整数.如果您需要检测负整数或分数,您应该使用更强大的基于库的解决方案.虽然,添加对负整数的支持非常简单.
As pointed out in the comments below, this only works for positive integers. If you need to detect negative integers or fractions, you should go with a more robust library-based solution. Although, adding support for negative integers is pretty trivial.
这篇关于如何确定字符串是否为 C++ 中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!