Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append formatted string to string in C without pointer arithmetic

I wrote a very simple C function to illustrate what I would like to simplify:

void main(int argc, char *argv[])
{
    char *me = "Foo";
    char *you = "Bar";
    char us[100];
    memset(us, 100, 0x00);

    sprintf(us, "You: %s\n", you);
    sprintf(us + strlen(us), "Me: %s\n", me);
    sprintf(us + strlen(us), "We are %s and %s!\n", me, you);
    printf(us);
}

Is there a standard library function to handle what I'm doing with sprintf and advancing the pointer?

like image 995
AJ. Avatar asked Dec 01 '22 06:12

AJ.


2 Answers

sprintf returns the number of non-NUL characters written.

int len = 0;
len += sprintf(us+len, ...);
len += sprintf(us+len, ...);
...
like image 125
ephemient Avatar answered Dec 06 '22 06:12

ephemient


char *me="Foo";
char *you="Bar";
char us[100];

char* out = us;
out += sprintf(out,"You: %s\n",you);
out += sprintf(out,"Me: %s\n",me);
out += sprintf(out,"We are %s and %s!\n",me,you);
printf("%s", us);
like image 37
Hans Passant Avatar answered Dec 06 '22 07:12

Hans Passant