如何使用C++确定字符串是否为数字? [英] How to determine if a string is a number with C++?

查看:30
本文介绍了如何使用C++确定字符串是否为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试编写一个检查字符串是否为数字的函数时遇到了很多麻烦.对于我正在编写的游戏,我只需要检查我正在读取的文件中的一行是否是数字(这样我就知道它是否是一个参数).我编写了以下我认为运行顺利的函数(或者我不小心编辑以阻止它或者我是精神分裂症或 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++确定字符串是否为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆