Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-29 13:06:29
Original
836 people have browsed it

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>
Copy after login

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"
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!