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!

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top