"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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`

Published on 2024-11-16
Browse:762

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.

#include 

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;
}

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:

#include 

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;
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3