snprintf for string concatenation

前端 未结 4 1857
一整个雨季
一整个雨季 2020-12-24 08:03

I am using snprintf to concatenate a string to a char array:

char buf[20] = \"\";
snprintf(buf, sizeof buf, \"%s%s\", buf, \"foo\");
printf(\"%s\\n\", buf);
         


        
4条回答
  •  抹茶落季
    2020-12-24 08:33

    Try this:

    char buf[20];
    snprintf(buf, sizeof buf, "%s", "foo");
    printf("%s\n", buf);
    int len = strlen(buf);
    snprintf(buf+len, (sizeof buf) - len, "%s", " bar");
    printf("%s\n", buf);
    

    Output is "foo bar". The first argument to snprintf, a pointer to a char, is where it will start stuffing the characters. It pays no attention to what is in the buffer already. The function strlen does pay attention though. It counts the number of characters before the nul (0) that snprintf put there. So instead of passing buf, pass buf+strlen(buf). You could also use strncat, which would be slightly more efficient.

    I see the tag C++ under your question. Look up std::string. Way better.

提交回复
热议问题