如何检查字符串是否可以在C++中转换为double?

hel*_*t91 4 c++ string double

我有一个字符串,可以是一个数字(甚至是浮点数或双精度型,不仅仅是整数),它也可以是一个非数字的单词.

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

我试过这个:

double tmp;
string str;
stringstream ss;

ss << str;
ss >> tmp;

if (ss.fail())
{
    // non-numeric string
}
else
{
    // string to double conversion is successful
}
Run Code Online (Sandbox Code Playgroud)

这段代码的问题在于ss.fail()始终true,即使tmp包含了正确的价值.

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

Ale*_*nko 7

如果您的输入字符串具有来自 std::string 的类型(它适用于 Windows 和 unix 系统),则可以使用此函数:

#include <stdlib.h>
#include <string>
/**
* @brief checkIsDouble - check inputString is double and if true return double result
* @param inputString - string for checking
* @param result - return double value
* @return true if string is double, false if not
*/
bool checkIsDouble(string inputString, double &result) {
    char* end;
    result = strtod(inputString.c_str(), &end);
    if (end == inputString.c_str() || *end != '\0') return false;
    return true;
}
Run Code Online (Sandbox Code Playgroud)


Ple*_*rts 5

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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


P0W*_*P0W 1

还要检查空白和流结尾

if ((ss >> tmp) && (ss >> std::ws).eof() )
{
   // a double

}
Run Code Online (Sandbox Code Playgroud)

提取一个double值,然后提取任何空格,如果在此期间遇到 eof,则意味着您有一个有效的double唯一