Convert Double to Char Array

Hi,

I am having a lot of trouble copying a double value 'x_pos' into a char array 'x_position_string'. I have been trying to use sprintf but i am getting an error in Output.c. Output.c IS NOT MY CODE.

This is the line with the error in Output.c

int hexadd=0; /* offset to add to number to get 'a'..'f' */

Here is my code

char x_position_string[10] = "empty";
double pos_x = position_vector[0];
sprintf(x_position_string, "%f", pos_x);

I don't think its as easy as that to convert a double to a string.
But here's a way using C++ stringstreams:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <string>
#include <cstring>
#include <sstream>
#include <iostream>

std::string to_string(double x);

int main()
{
  double pi = 3.14159;
  std::string str = to_string(pi);

  std::cout << str << std::endl;

  // Cstring:
  char digits[10];
  std::strcpy( digits, str.c_str() );

  std::cout << std::endl << "c-string:" << std::endl;
  std::cout << digits[2] << std::endl;
  std::cout << digits << std::endl;

  return 0;
}

std::string to_string(double x)
{
  std::ostringstream ss;
  ss << x;
  return ss.str();
}

I usually use a template function with a stringstream to do this but you'll have to wait for the experts opinions on the advantages/drawbacks compared to sprintf as I have no idea

1
2
3
4
5
6
7
template<Typename T>
std::string toString(T val)
{
    std::stringstream ss("");
    ss << val;
    return ss.str();
}


EDIT: Beaten to it

Last edited on
Topic archived. No new replies allowed.