Home > Article > Backend Development > How to Safely Convert Strings to Doubles in C and Handle Non-Numerical Strings?
Converting Strings to Doubles in C with Special Handling for Non-Numerical Strings
In C , converting strings to doubles can be done seamlessly using built-in functions. However, it becomes crucial to distinguish between numerical and non-numerical strings. To address this challenge, we present a solution that returns 0 for non-numerical strings.
Function Implementation:
The core of our solution lies in the string_to_double function:
<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>
How It Works:
Testing the Function:
In the provided test cases, we demonstrate how the function interprets different numeric and non-numeric strings correctly:
<code class="cpp">int main() { assert(0.5 == string_to_double("0.5")); assert(0.5 == string_to_double("0.5 ")); assert(0.5 == string_to_double(" 0.5")); assert(0.5 == string_to_double("0.5a")); // Non-numerical strings will return 0: assert(0 == string_to_double("foobar")); }</code>
Limitations:
It's important to note that due to the specific requirements of returning 0 for non-numerical strings, distinguishing between numerical strings representing zero and truly non-numerical strings is not possible.
The above is the detailed content of How to Safely Convert Strings to Doubles in C and Handle Non-Numerical Strings?. For more information, please follow other related articles on the PHP Chinese website!