How do I concatenate const/literal strings in C?

前端 未结 17 1489
醉梦人生
醉梦人生 2020-11-21 23:45

I\'m working in C, and I have to concatenate a few things.

Right now I have this:

message = strcat(\"TEXT \", var);

message2 = strcat(strcat(\"TEXT          


        
17条回答
  •  北海茫月
    2020-11-22 00:17

    Avoid using strcat in C code. The cleanest and, most importantly, the safest way is to use snprintf:

    char buf[256];
    snprintf(buf, sizeof buf, "%s%s%s%s", str1, str2, str3, str4);
    

    Some commenters raised an issue that the number of arguments may not match the format string and the code will still compile, but most compilers already issue a warning if this is the case.

提交回复
热议问题