如何打印相同的变量转换成字符串几次? [英] How can I print the same variable into a string several times?

查看:109
本文介绍了如何打印相同的变量转换成字符串几次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式字符串是这样的:

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

和我想插入每个%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);

我可以在只要求我写 VAL 键和<$ C $的方式使用的sprintf C>的sprintf 将使用它的每个%d个

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

推荐答案

是的,你可以使用%1 $ d个每次。在 $ 1 引用的第二个参数,你可以明显与其他参数做到这一点。

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

演示: HTTP://$c$cpad.org/xVmdJkpN

请注意,该位置说明是一个POSIX扩展 - 因此它可能无法与每一个编译器工作。如果你需要它的工作如使用Visual C ++编译器,可以考虑使用重复争论的丑陋的方式或不使用printf样式的功能都没有。另一种选择是使用POSIX兼容的sprintf实现或使用多个电话要追加一个数字,每次在一个循环的情况下(格式字符串动态地建立了将美元,指定正确数量的参数p $ pvent你)。

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

在一个侧面说明,应避免的sprintf 。使用的snprintf(BUF2,sizeof的(BUF2),....)来代替。当然,这需要 BUF2 有在编译时已知的静态尺寸 - 但是如果你手动分配它,你可以简单地使用含有长度而不是<$ C $的变量C>的sizeof(BUF2)。

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

这篇关于如何打印相同的变量转换成字符串几次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆