How can I make this print properly without using two printf calls?
char* second = "Second%d";
printf("First%d"second,1,2);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The code you showed us is syntactically invalid, but I presume you want to do something that has the same effect as:
As you know, the first argument to
printfis the format string. It doesn’t have to be a literal; you can build it any way you like.Here’s an example:
Some notes:
I’ve added a newline after the output. Output text should (almost) always be terminated by a newline.
I’ve set an arbitrary size of 100 bytes for the format string. More generally, you could declare
and initialize it with a call to
malloc(), allocating the size you actually need (and checking thatmalloc()didn’t signal failure by returning a null pointer); you’d then want to callfree(format);after you’re done with it.As templatetypedef says in a comment, this kind of thing can be potentially dangerous if the format string comes from an uncontrolled source.
(Or you could just call
printftwice; it’s not that much more expensive than calling it once.)