Home > Article > Backend Development > How Can I Convert Strings to Double Values in C while Handling Non-Numerical Inputs?
Converting Strings to Double Values in C
Problem Statement:
Convert a string representation of a number to a floating-point double value. If the string is not numerical, return 0.
Solution:
To convert a string to a double value in C , you can use the std::stod function, which takes a string parameter and converts it to a double. However, this function does not return 0 for non-numerical strings.
Custom Function for Non-Numerical Handling:
To address this, we can create a custom function that returns 0 for non-numerical strings. Here's an implementation:
<code class="cpp">#include <sstream> double string_to_double(const std::string& s) { std::istringstream i(s); double x; if (!(i >> x)) { return 0; } return x; }</code>
This function uses std::istringstream to extract the double value from the string. If the extraction fails, it returns 0.
Usage Examples:
Here are some examples of using the string_to_double function:
<code class="cpp">assert(0.5 == string_to_double("0.5")); assert(0.5 == string_to_double("0.5 ")); assert(0.5 == string_to_double("0.5a")); assert(0 == string_to_double("foobar"));</code>
Note Regarding Non-Numerical Zeroes:
It's important to note that this function cannot distinguish all non-numerical strings from zeros. For example, the following strings are all considered as zeros according to this implementation:
The above is the detailed content of How Can I Convert Strings to Double Values in C while Handling Non-Numerical Inputs?. For more information, please follow other related articles on the PHP Chinese website!