Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c - How can I print the same variable into a string several times?

I have a format string like this:

buf[] = "A%d,B%d,C%d,D%d,F%d,G%d,H%d,I%d,J%d";

and I want to insert the same integer for each %d so I use:

 int val = 6;
 sprintf(buf2, buf, val,val,val,val,val,val,val,val,val);

Can I use sprintf in a way that only requires me to write val once, and sprintf will use it for each %d?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can use %1$d everytime. The 1$ references the second argument, you could obviously do it with other arguments, too.

Demo: http://codepad.org/xVmdJkpN

Note that the position specifier is a POSIX extension - so it might not work with every single compiler. If you need it to work e.g. with the Visual C++ compiler, consider using the ugly way of repeating the argument or do not use a printf-style function at all. Another option would be using a POSIX-compatible sprintf implementation or using multiple calls to append one number everytime in a loop (in case the format string is built dynamically which would prevent you from specifying the correct number of arguments).


On a side-note, sprintf should be avoided. Use snprintf(buf2, sizeof(buf2), ....) instead. Of course this requires buf2 to have a static size known at compile-time - but if you allocate it manually you can simply use the variable containing the length instead of sizeof(buf2).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...