如何验证字符串是否为有效的双精度型(即使其中有一个点)? [英] How do i verify a string is valid double (even if it has a point in it)?

查看:188
本文介绍了如何验证字符串是否为有效的双精度型(即使其中有一个点)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整夜忙于寻找一种方法来确定我的字符串值是否为有效的双精度数,但我还没有找到一种方法也不会拒绝带有点的数字...

I have been up all night searching for a way to determine if my string value is a valid double and I haven't found a way that will also not reject a number with a point in it...

在搜索中我发现了

How to determine if a string is a number with C++?

查尔斯·萨尔维亚(Charles Salvia)给出的答案是

and the answer that Charles Salvia gave was

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();
}

此功能适用于任何不带点但为a的数字带有点的数字会被拒绝...

this works for any number that doesn't have a point in it but a number with a point gets rejected...

推荐答案

您可以使用 strtod

You can use strtod:

#include <cstdlib>

bool is_number(const std::string& s)
{
    char* end = nullptr;
    double val = strtod(s.c_str(), &end);
    return end != s.c_str() && *end == '\0' && val != HUGE_VAL;
}

您可能会想使用 std :: stod 像这样:

You may be tempted to use std::stod like this:

bool is_number(const std::string& s)
{
    try
    {
        std::stod(s);
    }
    catch(...)
    {
        return false;
    }
    return true;
}

但这效率可能很低,例如零成本例外

but this can be quite inefficient, see e.g. zero-cost exceptions.

这篇关于如何验证字符串是否为有效的双精度型(即使其中有一个点)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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