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.
Description. The C library function double strtod(const char *str, char **endptr) converts the string pointed to by the argument str to a floating-point number (type double). If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.
The strtod() is a builtin function in C and C++ STL which interprets the contents of the string as a floating point number and return its value as a double. It sets a pointer to point to the first character after the last valid character of the string, only if there is any, otherwise it sets the pointer to null.
We can convert a char array to double by using the std::atof() function.
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.
You can use this function if your input string have type from std::string (it works on windows and unix systems):
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With