strcat() for formatted strings

前端 未结 6 1439
予麋鹿
予麋鹿 2021-02-20 05:37

I\'m building a string piece by piece in my program and am currently using a mix of strcat() when I\'m adding a simple string onto the end, but when im adding a formatted string

6条回答
  •  甜味超标
    2021-02-20 06:13

    Your solution will work. Calling strlen is a bit awkward (particularly if the string gets quite long). sprintf() will return the length you have used [strcat won't], so one thing you can do is something like this:

     char str[MAX_SIZE];
     char *target = str;
    
     target += sprintf(target, "%s", str_value);
     target += sprintf(target, "somestuff %d", number);
     if (something)
     {
        target += sprintf(target, "%s", str_value2);
     }
     else
     {
        target += sprintf(target, "%08x", num2);
     }
    

    I'm not sure strcat is much more efficient than sprintf() is when used in this way.

    Edit: should write smaller examples...

提交回复
热议问题