concatenate variables with commas printf

自古美人都是妖i 提交于 2019-12-23 05:24:34

问题


Hi I have a C program which has two variables

int a = 1;
int b = 2;

where I want to use printf to print:

1,2

so i can plug the result into a csv file.

I have tried:

printf("f\n","f\n", a,",",b);

however this doesn't work.

If I try without adding the comma:

printf("f\n","f\n", 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.

thanks for any help!


回答1:


Like this:

printf("%d,%d\n", a, b);

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

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.

Hint: have a look at printf() manpage.




回答2:


You can use the following:

printf("%d,%d\n", a, b);


来源:https://stackoverflow.com/questions/23637714/concatenate-variables-with-commas-printf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!