Home >Backend Development >C++ >How to Convert Strings to Doubles in C : A Simple Guide Using `std::istringstream` and `std::stod`

How to Convert Strings to Doubles in C : A Simple Guide Using `std::istringstream` and `std::stod`

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 13:06:29914browse

How to Convert Strings to Doubles in C  : A Simple Guide Using `std::istringstream` and `std::stod`

Converting Strings to Doubles in C

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:

  1. Create an std::istringstream object iss from the input string s.
  2. Use the >> operator to extract a double value from iss.
  3. If the extraction is successful, return the double value.
  4. If the extraction fails (e.g., the string is not numerical), return 0.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn