gpt4 book ai didi

c++ - 我如何验证一个字符串是否有效(即使它有一个点)?

转载 作者:可可西里 更新时间:2023-11-01 15:40:03 25 4
gpt4 key购买 nike

我整晚都在寻找一种方法来确定我的字符串值是否是有效的 double 值,但我还没有找到一种方法也不会拒绝其中包含一个点的数字...

在我的搜索中我找到了这个

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

而Charles Salvia给出的答案是

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

这适用于任何没有点的数字,但有点的数字会被拒绝...

最佳答案

您可以使用 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像这样:

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

但这可能效率很低,参见例如zero-cost exceptions .

关于c++ - 我如何验证一个字符串是否有效(即使它有一个点)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29169153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com