如何检查字符串是否可以在C ++中转换为双精度? [英] How to check if a string can be converted to double in C++?

查看:85
本文介绍了如何检查字符串是否可以在C ++中转换为双精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,可以是一个数字(甚至是一个float或double类型,不仅是整数),它也可以是一个非数字的单词。



我想检查这个字符串是否可以转换成double,如果是这样,那么我想做转换。如果是非数字字符串,我想要不同的行为。



我已经尝试过:

  double tmp; 
string str;
stringstream ss;

ss<<海峡;
ss>> TMP;

if(ss.fail())
{
//非数字字符串
}
else
{
// string to double conversion was successful
}

此代码的问题是 ss.fail()始终是 true ,即使 tmp 包含正确的值。



有一个名为 atof()的函数,它将字符串转换为double,但这是不适合我,如果输入的字符串是非数字的,则它返回 0.0 的值。这样我就无法区分非数字和零输入值。

解决方案

std :: stod怎么样?当它无法执行转换时,会抛出std :: out_of_range。

  try 
{
double value = std :: stod(input_string);
std :: cout<<< 将字符串转换为值<<值<<的std :: ENDL;
}
catch(std :: exception& e)
{
std :: cout<<< 无法将字符串转换为double<<的std :: ENDL;
}

我没有尝试编译它,但你应该得到想法。


I have a string which can be a number (even a float or double type, not only integer), and it can be also a word which is non-numeric.

I would like to check if this string can be converted into double, and if so, then I would like to do the conversion. In case of a non-numeric string, I want different behaviour.

I have tried this:

double tmp;
string str;
stringstream ss;

ss << str;
ss >> tmp;

if (ss.fail())
{
    // non-numeric string
}
else
{
    // string to double conversion is successful
}

The problem with this code is that ss.fail() is always true, even if tmp contains the right value.

There is a function called atof() which converts string to double, but this is not suitable for me, becouse it returns 0.0 value if the input string is non-numeric. This way I cannot make difference between a non-numeric and a zero input value.

解决方案

What about std::stod? It will throw std::out_of_range when it can't perform the conversion.

try
{
    double value = std::stod(input_string);
    std::cout << "Converted string to a value of " << value << std::endl;
}
catch(std::exception& e)
{
    std::cout << "Could not convert string to double" << std::endl;
}

I haven't tried to compile it, but you should get the idea.

这篇关于如何检查字符串是否可以在C ++中转换为双精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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