Best / common practice for delimiting values ​​in C when printing them

I tried the search function, but only found questions regarding reading in comma-delimited / space-separated files.

My question, however, is how you usually approach this. Say I have a list of / array / ... values, for example {1, 2, 3, 4}, and you want to print them using a separator.

The simplest version will look something like this:

#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 with this is the comma and the space 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;
}

This does not seem to be the best way to do this. Can someone point me in the right direction? Thanks

PS: No, usually there are no hard code values.
PPS: No, I'm not trying to write .csv files;)

+3
7

:

assert(n > 0);
printf("%d", list[0]);
for (i = 1; i < n; ++i)
     printf(", %d", list[i]);

, n == 0, . , n == 0:

if (n > 0)
    printf("%d", list[0]);
for (i = 1; i < n; ++i)
     printf(", %d", list[i]);
+4

:

const char *pad = "";
for (int i = 0; i < n; i++)
{
    printf("%s%d", pad, list[i]);
    pad = ", ";
}

- .

+11

K & R2:

for (i = 0; i < n; i++)
    printf("%d%s", list[i], i+1 < n ? ", " : "\n");
+2

, , :

#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;
}
+1

Michal Trybus

for (i = 0; i < (n - 1); ++i) 
{
     printf("%d, ", list[i]);
}
printf("%d", list[n - 1]);
0
for ( printf("%d",list[i=0]) ; i < n ; printf(", %d", list[++i]) ) ;
0

, .

for (i=0;i<n;++i)
{
  if (i) printf(", ");
  printf("%d",list[i]);
}
0

Source: https://habr.com/ru/post/1769593/


All Articles