I tried the search func开发者_运维问答tion but only found questions regarding reading in comma/space delimited files.
My question is however, how do you usually approach this. Say I have a list/array/... of values, like {1, 2, 3, 4} and want to print them with a delimiter.
The simplest version would be something like:
#include <stdio.h>
int main(void)
{
char list[] = {1, 2, 3, 4};
unsigned int i;
for (i = 0; i < 4; ++i)
printf("%d, ", list[i]);
return 0;
}
which will obviously print "1, 2, 3, 4, ". The problem I have with that is the comma and space character at the end.
Now I could do:
#include <stdio.h>
int main(void)
{
char list[] = {1, 2, 3, 4};
unsigned int i;
for (i = 0; i < 4; ++i)
{
printf("%d", list[i]);
if (i < 3)
printf(", ");
}
return 0;
}
Bút that doesn't seem like the best way to do it. Can somebody point me into the right direction? Thanks
PS: No, I don't usually hardcode values
PPS: No, I am not trying to write .csv files ;)My standard technique for this is:
const char *pad = "";
for (int i = 0; i < n; i++)
{
printf("%s%d", pad, list[i]);
pad = ", ";
}
Sometimes, the initial value of pad is a blank, or a colon blank, or whatever else works in context.
I use this idiom:
assert(n > 0);
printf("%d", list[0]);
for (i = 1; i < n; ++i)
printf(", %d", list[i]);
Its one disadvantage is that it doesn't scale nicely for n == 0, like a simple loop. Alternatively, you can add protection against n == 0:
if (n > 0)
printf("%d", list[0]);
for (i = 1; i < n; ++i)
printf(", %d", list[i]);
I picked up this format with the conditional operator from K&R2:
for (i = 0; i < n; i++)
printf("%d%s", list[i], i+1 < n ? ", " : "\n");
Well even thought there is already an accepted answer, nobody has come with the obvious one to my taste:
#include <stdio.h>
int main(void) {
unsigned list[] = {1, 2, 3, 4};
unsigned const n = 4;
if (n) for (unsigned i = 0; ; ++i) {
printf("%d", list[i]);
if (i >= n) break;
printf(", ");
}
printf("\n");
return 0;
}
Use Michal Trybus's version or the reverse
for (i = 0; i < (n - 1); ++i)
{
printf("%d, ", list[i]);
}
printf("%d", list[n - 1]);
for ( printf("%d",list[i=0]) ; i < n ; printf(", %d", list[++i]) ) ;
Why not just another version while we're at it. Here's what I normally do
for (i=0;i<n;++i)
{
if (i) printf(", ");
printf("%d",list[i]);
}
精彩评论