问题
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