c - Variable placeholders in a char * -


i have following c example:

char *message; char *name = "john"; int age = 100;  message = "hello, john, age 100";  

how put name , age parameters in message?

pseudo codemessage = "hello, {name}, age {age}"

update

i tried following example comments:

char *body = "{ \"capabilities\": {},\"desiredcapabilities\": {}}"; int content_length = sizeof(body);  char *format = "post /session http/1.1\r\ncontent-type: application/json\r\ncontent-length:%d\r\n\r\n%s"; int len = snprintf(null, 0, format, content_length, body); char *message = malloc(len + 1); snprintf(message, len + 1, format, content_length, body); 

but getting error @ char *message = malloc(len + 1);:

error: invalid conversion ‘void*’ ‘char*’ [-fpermissive]|

you can snprintf. works printf, puts result string instead of writing stdout.

char message[100]; snprintf(message, sizeof(message), "hello, %s, age %d", name, age); 

note example uses fixed size buffer. if want dynamically allocate space, this:

const char *format = "hello, %s, age %d"; int len = strlen(format) + strlen(name) + sizeof(age)*3 + 1; char *message = malloc(len); snprintf(message, len, "hello, %s, age %d", name, age); // ... free(message); 

this sets aside space format string, each parameter, , terminating null byte.

another way of getting needed length call snprintf twice, first time null string , 0 size. return value length of resulting string:

const char *format = "hello, %s, age %d"; int len = snprintf(null, 0, "hello, %s, age %d", name, age); char *message = malloc(len + 1); snprintf(message, len + 1, "hello, %s, age %d", name, age); // ... free(message); 

regarding error in updated code, you're apparently using c++ compiler instead of c compiler. if you're writing c, use c compiler.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -