I'm working on a bare-bones Blackjack game that uses sockets, courtesy of my Operating Systems class. We were given a socket interface already which passes an array of characters back and forth.
I had hoped I could do something like this:
char[] msgOut = printf("Dealer's Card is %C %C", char1, char2);
sendMsg(msgOut);
HOWEVER, googling lead me to determine that the return value of printf is an int of the number of Char's output, not a char[] of the chars themselves (as I had hoped).
Is there another C function that lets me build strings from my variables?
How to create a string and assign it to a variable. To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable.
C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.
using printf() If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings. The complete syntax for this method is: printf("%s", char *s);
printf
writes to standard output. snprintf
accomplishes what you are going for here. The interpolated string is stored in 'buffer' after the call to snprintf. You may want define your buffer size a little more intelligently, but this is just an example.
char buffer[1024];
snprintf(buffer, sizeof(buffer), "Dealer's Card is %C %C", char1, char2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With