Reputation: 2993
I have a long array position
and in writing it as a single column I can do the following:
FILE *f = fopen("testing.txt", "w");
for (i=0; i<18; i++){
fprintf(f,"%d\n",position[i]);
}
The output (in testing.txt) is like:
1
3
3
5
6
7
0
37
8
34
5
3
5
6
3
1
7
8
How can I print to file as:
1 7 5 1
3 0 3 7
3 37 5 8
5 8 6
6 34 3
as multiple columns each has maximum length 5?
Upvotes: 0
Views: 2873
Reputation: 1
fprintf(f,"%d %d...%d\n",position[i],position[i+1]...position[i+n-1]);
but first fix your loop
Upvotes: 0
Reputation: 170
Original code
FILE *f = fopen("testing.txt", "w");
for (i=0; i<18; i++){
fprintf(f,"%d\n",position[i]);
}
My guess for your request, if I understood it correctly, would be like this:
#include <stdio.h>
#include <stdlib.h>
int main (){
int v[18] = {1,3,3,5,6,7,0,37,8,34,5,3,5,6,3,1,7,8};
int i = 0, adder = 0, done = 0;
while (1){
if (done == 19)
break;
done++;
if (i <= 18){
printf("%d ", v[i]);
i = i+5;
}
if (i > 18){
printf("\n");
adder++;
i = adder;
}
}
}
You can add the file yourself. If you want an explanation, basically what I did was consider that we only have your 18 elements, and while I was not done with all of them, i counted each time I printed one of them, and when I printed them I made sure to print from 5 to 5 so that would be in a matrix form.
Upvotes: 0
Reputation: 342
your output is a little strange you have 4 elements in first and second line, and three elements in third and forth line. In general to maintain in the same line you can print " " or '\t' - tab
printf("%d ", 1);
printf("%d", 2);
or
printf("%d\t", 1);
printf("%d", 2);
When you need to make a new line you use '\n' (like you are using) You have to know how much elements that you need in each particular line to force then '\n'
Upvotes: 0
Reputation: 40145
like this
#include <stdio.h>
int main(void){
int pos[] = {
1,3,3,5,6,
7,0,37,8,34,
5,3,5,6,3,
1,7,8
};
int len = sizeof(pos)/sizeof(*pos);
int col_len = 5;
for(int i = 0; i < col_len; ++i){
for(int j = i; j < len; j += col_len){
printf("%2d ", pos[j]);//fprintf(f, "%2d ", pos[j])
}
puts("");
}
}
Upvotes: 2