0

I'm working on a code to create my own printf. The use of printf, sprintf, and the like are prohibited. I need to convert a double type variable to a char type variable in order to use it in a puts() function with prefixes and other things added. How do I turn a double into a string?

I found this earlier, but it only converts the memory of the variable to a string:

#include <string.h>
double a=2.132;
char arr[sizeof(a)];
memcpy(arr,&a,sizeof(a));

What can I do to make this a variable? So far, the snippet of my code where I integrated that looks like this:

double num = 10.99;
char arr[sizeof(num)];
memcpy(arr, &num, sizeof(num));
puts(arr);

//Expected output: 10.99
//Actual output:

doesn't work and will return nothing to the console. If anyone could point me in the right direction, that would be much appreciated!

  • Can you use `floor` et. al.? – Craig Estey Feb 10 '22 at 20:33
  • What are you trying to do? To get a string representing the number? Or an array of bytes composing the `double` number in the memory? These are two different things. – Eugene Sh. Feb 10 '22 at 20:36
  • 1
    Consider converting double to a string as _extremely hard_. You can use `strfromd` instead of `printf*`. – KamilCuk Feb 10 '22 at 20:37
  • 1
    There are some useful comments (if not an actual answer) at the previous question [how to convert a float number to string to print it using write() function in C](https://stackoverflow.com/questions/69248148). – Steve Summit Feb 10 '22 at 20:37
  • 1
    Have you solved the related problem, `Convert an int to a char type variable without using sprintf`? If not, I suggest starting there. – Steve Summit Feb 10 '22 at 20:39
  • It won't solve the problem, but when you converted the number to a string you didn't add a null terminator. – Barmar Feb 10 '22 at 21:18
  • @EugeneSh. The first sentence of the question says what she's trying to do: Write her own implementation of `printf()`. That clearly means she wants to get a string representing the number. – Barmar Feb 10 '22 at 21:19

0 Answers0