开发者

fprintf - Print a specific numbers of characters per line

开发者 https://www.devze.com 2023-02-13 12:33 出处:网络
For example I have some x,y coordinate. How can I print multiple x,y on the screen so that I have only 4 of these coordinates per line.

For example I have some x,y coordinate. How can I print multiple x,y on the screen so that I have only 4 of these coordinates per line.

So let us say that all x and y are the same throughou开发者_JAVA技巧t and I want this printed out where x = 1 and y = 2.

1 2 1 2 1 2 1 2
1 2 1 2 1 2 1 2
1 2 1 2 1 2 1 2
..............

Fprintf(?)


Since you want exactly four per line, just do this:

printf("%d %d %d %d %d %d %d %d\n", x, y, x, y, x, y, x, y);

for as many lines as you want.


Let's say you have something like this:

typedef struct point {
    int x;
    int y;
} point_t ;

#define NUM_OF_LINES 5
#define POINTS_PER_LINE 4

int main( void ) {
    point_t p[NUM_OF_LINES][POINTS_PER_LINE];

    //  fill points with valid data somehow

    // print points
    for (int i = 0; i != NUM_OF_LINES; i++) {
        for( int j = 0; j != POINTS_PER_LINE; j++ )
            printf("%d %d ", p[i][j].x, p[i][j].y);

        printf("\n");
    }

}


for (int i=0; i<total_points; i++) {
    printf("%d %d", points[i].x, points[i].y);
    if (i % points_per_line == 0)
        printf("\n");
    else
        printf(" ");
}

...or, if you don't mind code that some might consider slightly "tricky":

static char seps[] = {'\n', ' '};

for (int i=0; i<total_points; i++)
    printf("%d %d%c", 
        points[i].x,
        points[i].y,
        seps[(i%points_per_line)==0]);

Either way, these obviously presume something like the normal definition of a point, something on the order of:

typedef struct { 
    int x;
    int y;
} point;
0

精彩评论

暂无评论...
验证码 换一张
取 消