Home  >  Article  >  Backend Development  >  How to Safely Convert Strings to Doubles in C and Handle Non-Numerical Strings?

How to Safely Convert Strings to Doubles in C and Handle Non-Numerical Strings?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 07:28:301004browse

How to Safely Convert Strings to Doubles in C   and Handle Non-Numerical Strings?

Converting Strings to Doubles in C with Special Handling for Non-Numerical Strings

In C , converting strings to doubles can be done seamlessly using built-in functions. However, it becomes crucial to distinguish between numerical and non-numerical strings. To address this challenge, we present a solution that returns 0 for non-numerical strings.

Function Implementation:

The core of our solution lies in the string_to_double function:

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

How It Works:

  1. We create an input string stream (std::istringstream) object i for safely reading the string.
  2. We attempt to extract a double from the stream. If successful, the double is assigned to x.
  3. If no double can be extracted (i >> x fails), we return 0, indicating a non-numerical string.

Testing the Function:

In the provided test cases, we demonstrate how the function interprets different numeric and non-numeric strings correctly:

<code class="cpp">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"));

  // Non-numerical strings will return 0:
  assert(0 == string_to_double("foobar"));
}</code>

Limitations:

It's important to note that due to the specific requirements of returning 0 for non-numerical strings, distinguishing between numerical strings representing zero and truly non-numerical strings is not possible.

The above is the detailed content of How to Safely Convert Strings to Doubles in C and Handle Non-Numerical Strings?. 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