Home > Blockchain >  Add const char and char in c
Add const char and char in c

Time:08-12

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?

CodePudding user response:

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.

CodePudding user response:

  • Using char player as an argument to strcat_s is not valid. It requires a, possibly const, char*.
  • The second argument to the _s functions you use should be the number of elements in your char array.

Example:

#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>

int main() {
    char string[30];
    const char *player = "x";

    strcpy_s(string, sizeof string, "Player ");
    strcat_s(string, sizeof string, player);
    strcat_s(string, sizeof string, " won\n");
    
    puts(string); // prints "Player x won"
}

... but do not do this. It's a very inefficient way to build your final string. Instead do what Silvio Mayolo suggests in his answer.

CodePudding user response:

Using sprintf it can be done simply like

sprintf( string, "%s%c%s", "Player ", player, " won\n" );

or using snprintf

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