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

查看:195
本文介绍了如何确定字符串是否是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的方式: p>

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(), [](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天全站免登陆