Search code examples
ccharc-stringsstring.h

Add const char and char in c


I have a player char player = x; and want to overwrite a string char string[30]; to contain "Player" + player + "won". I tried

strcpy_s(string, "Player ");
strcat_s(string, player);
strcat_s(string, " won\n");

but obviously this doesn't work, because char is not compatible with const char

How can I do it instead?


Solution

  • You're looking for snprintf, your general purpose string-formatting stdlib function.

    snprintf(string, sizeof(string), "Player %c won\n", player);
    

    You can read all about the different % formatting directives available in the above link, but %c is the one you want for characters.