用逗号printf连接变量 [英] concatenate variables with commas printf
问题描述
我有一个带有两个变量的C程序
Hi I have a C program which has two variables
int a = 1;
int b = 2;
我要使用printf打印的位置:
where I want to use printf to print:
1,2
这样我可以插入结果
我尝试过:
printf("f\n","f\n", a,",",b);
但是这不起作用。
如果我尝试不添加逗号:
If I try without adding the comma:
printf("f\n","f\n", a,b);
仅打印变量a。因此,确实存在两个问题-如何在同一行上同时打印a和b,但更好的是如何用逗号分开打印它们。
it only prints out variable a. so really there are two problems - how do i print out both a and b on the same line, but even better how to i print them out separated by a comma.
谢谢您的帮助!
推荐答案
就像这样:
printf("%d,%d\n", a, b);
printf()
要求后面跟随一个格式字符串可变数量的参数(至少与格式化字符串中的修饰符数量一样)。这就是您的代码无法正常工作的原因:
printf()
expects a formatting string followed by a variable number of arguments (at least as much as the number of modifiers in the formatting string). That's why your code doesn't work:
printf("f\n","f\n", a,",",b);
此处,格式字符串为 f\n
,没有修饰符,因此从不使用其他参数。第二种方法也是如此。
Here, the formatting string is "f\n"
, there are no modifiers, so the other arguments are never used. The same applies to your second approach.
提示:请查看 printf()
联机帮助页。
Hint: have a look at printf()
manpage.
这篇关于用逗号printf连接变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!