Ad

Can I Continue To Writing To A String With Printf() After The ','?

- 1 answer

//Assume "char str[n]" declared & initialized
printf("The String \"%s\"",str);
printf("contains %d bytes in RAM", sizeof(str));

Is there a way to write this code like in the below Java format in C language?

System.out.println("The String " + str + " contains " +  sizeof(str) + " bytes in RAM"); //I know there is no //sizeof(...) in Java, i just wrote it to demonstrate :D
Ad

Answer

You can provide more than one format specifier and more than one value to printf()

printf("The String %s contains %d bytes in RAM", str, sizeof(str));

As was pointed out in the comments, there's an error in your code. sizeof(str) will only give you the size of the variable, not the length of the string. What you're actually looking for is strlen(str) instead.

printf("The String %s contains %zu in RAM", str, strlen(str));
Ad
source: stackoverflow.com
Ad