Home >Backend Development >C++ >How to Convert Strings to Doubles in C : A Simple Guide Using `std::istringstream` and `std::stod`
In C , converting a string to a double can be achieved using the std::istringstream and std::stod functions.
<code class="cpp">#include <sstream> double string_to_double(const std::string& s) { std::istringstream iss(s); double x; if (!(iss >> x)) { return 0; // Return 0 for non-numerical strings } return x; }</code>
Here's how this function works:
Note that this function cannot fully distinguish all allowed string representations of zero from non-numerical strings. For example, it considers all the following strings as zero:
"0" "0." "0.0"
Here are some test cases to demonstrate the usage of the string_to_double function:
<code class="cpp">#include <cassert> 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")); assert(0 == string_to_double("0")); assert(0 == string_to_double("0.")); assert(0 == string_to_double("0.0")); assert(0 == string_to_double("foobar")); return 0; }</code>
The above is the detailed content of How to Convert Strings to Doubles in C : A Simple Guide Using `std::istringstream` and `std::stod`. For more information, please follow other related articles on the PHP Chinese website!