Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building Strings from variables in C

Tags:

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?

like image 480
Raven Dreamer Avatar asked Feb 03 '11 01:02

Raven Dreamer


People also ask

How do I make a variable into a string?

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.

Can you assign a string to a variable in C?

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.

How do you print strings in C?

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);


1 Answers

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);
like image 194
Ed S. Avatar answered Oct 23 '22 20:10

Ed S.