3 ways of appending string to char

Solution 1: sprintf

 

/* sprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}

Solution 2: asprintf

/* asprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int a=5, b=3;
  n=asprintf (&buffer, "%d plus %d is %d", a, b);
  printf ("[%s] is a string\n",buffer);
  return 0;
}

 

Solution 3:

/* sprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *