Home > Backend Development > C++ > body text

How Can I Convert Strings to Double Values in C while Handling Non-Numerical Inputs?

Patricia Arquette
Release: 2024-10-31 08:07:29
Original
931 people have browsed it

How Can I Convert Strings to Double Values in C   while Handling Non-Numerical Inputs?

Converting Strings to Double Values in C

Problem Statement:

Convert a string representation of a number to a floating-point double value. If the string is not numerical, return 0.

Solution:

To convert a string to a double value in C , you can use the std::stod function, which takes a string parameter and converts it to a double. However, this function does not return 0 for non-numerical strings.

Custom Function for Non-Numerical Handling:

To address this, we can create a custom function that returns 0 for non-numerical strings. Here's an implementation:

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

This function uses std::istringstream to extract the double value from the string. If the extraction fails, it returns 0.

Usage Examples:

Here are some examples of using the string_to_double function:

<code class="cpp">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("foobar"));</code>
Copy after login

Note Regarding Non-Numerical Zeroes:

It's important to note that this function cannot distinguish all non-numerical strings from zeros. For example, the following strings are all considered as zeros according to this implementation:

  • "0"
  • "0."
  • "0.0"
  • " 0"
  • "-0"

The above is the detailed content of How Can I Convert Strings to Double Values in C while Handling Non-Numerical Inputs?. 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