Domanda

I have information stored in an array of char and I would like to pass them to a single double value. As an example, I want to pass it from,

data[0]=3;
data[1]=.;
data[2]=1;
data[3]=4;
data[4]=1;
data[5]=5;
data[6]=1;

to

double data = 3.14151;

How can I do it? Thanks!

È stato utile?

Soluzione

You can use functions std::stringstream from sstream or strtod from cstdlib or stod (If you are using C++11) as per your need.

Quoting example from cplusplus.com

// stod example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stod

int main ()
{
  std::string orbits ("365.24 29.53");
  std::string::size_type sz;     // alias of size_t

  double earth = std::stod (orbits,&sz);
  double moon = std::stod (orbits.substr(sz));
  std::cout << "The moon completes " << (earth/moon) << " orbits per Earth year.\n";
  return 0;
}

Altri suggerimenti

I am assuming that your array actually contains characters and you just forgot the apostrophs. I used an easier, less error-prone way to initialize data, with the added benefit that my version actually does a zero-termination, which yours didn't (as Axel correctly pointed out).

char const * data = "3.1415";

The solution would be:

#include <cstdlib>

// ...
double number = std::strtod( data, NULL );
// ...

Check the strtod() documentation for behaviour in case of error, and how to use the second parameter to check if your conversion actually went as far as you expected.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top