convert int to C string pointer

advertisements

Write a function the gets two strings and number, the signiture of the function: void get_formated_integer(char *format, char *result, int num) the function convert the given number num according the format and returns a string in the variable result, for %b converts int to binary of the number, for example, for the call: get_formated_integer("%b",&result, 18); then *result will get the string 10010

My code:

   #include <stdio.h>
  void convert_binary(int num)//converts decimal number to binary
{
    if(num>0)
    {
    convert_binary(num/2);
    printf("%d", num%2);
    }

}

void get_formated_integer(char *format, char *result, int num)
{
    if(format[1]=='b')
      convert_binary(num);
}

int main()
{
    char result[100];
    get_formated_integer("%b",&result, 18);
}

My output:

10010

I don't understand how to do that *result will get the string 10010

sorry about my English


First, replace

void convert_binary(int num)//converts decimal number to bi

with

void convert_binary(int num, char * result) //converts decimal number to binary

for the sake to have a place (result) for storing the result.


Second, replace its body - recursive calling and direct printing

{
    if(num>0)
    {
    convert_binary(num/2);
    printf("%d", num%2);
    }
}

with

{
    static int i = 0;              // Offset in result for storing the current digit
    if(num>0)
    {
        convert_binary(num/2, result);
        sprintf(result+i, "%d", num % 2);
        ++i;
    } else
        i = 0;
}

i.e. with statements for recursive call (updated function) and storing partial values.


Third, following previous changes, replace your original definition

void get_formated_integer(char *format, char *result, int num)
{
    if(format[1]=='b')
      convert_binary(num);
}

with

void get_formated_integer(char *format, char *result, int num)
{
    if(format[1]=='b')
        convert_binary(num, result);       // Only this is different
}


Four, put at the end in your main() function the statement for printing the result (as we changed direct printings in recursive calls to storing):

    printf("%s\n", result);