This tutorial will discuss about a unique way to check if a string can be converted to a double in C++.
To check if a string contains a valid double value or not, we can try to convert the string into a double using stod()
function. If the conversion is successful, then we can confirm that string can be converted into a double. Whereas, if string contains any invalid_argument
or some out_of_range
value then it will throw an exception. In case we encounter an exception while converting a string to double using the stod() function, then we can confirm that string cannot be converted into a double.
Let’s see the complete example,
#include <iostream> #include <string> using namespace std; // Check if string can be converted to a Double bool isDouble(const string& str) { bool result = true; try { // Convert string to double double d = stod(str); } catch (const invalid_argument& e) { // handle the exceptiop invalid_argument result = false; } catch (const out_of_range& e) { // handle the exceptiop out_of_range result = false; } return result; } int main() { string strValue = "8.907"; // Check if string can be converted into a double if (isDouble(strValue)) { cout << "Yes, string can be converted to a double" << endl; } else { cout << "No, string can not be converted to a double" << endl; } return 0; }
Output :
Yes, string can be converted to a double
Summary
Today we learned about several ways to check if a string can be converted to a double in C++. Thanks.