I tried the search function 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 😉
I use this idiom:
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: