gpt4 book ai didi

C:以多列形式写入文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:11 25 4
gpt4 key购买 nike

我有一个很长的数组 position 并且将它写成一个列我可以执行以下操作:

FILE *f = fopen("testing.txt", "w"); 
for (i=0; i<18; i++){
fprintf(f,"%d\n",position[i]);
}

输出(在 testing.txt 中)如下:

1
3
3
5
6
7
0
37
8
34
5
3
5
6
3
1
7
8

如何将文件打印为:

1 7 5 1
3 0 3 7
3 37 5 8
5 8 6
6 34 3

作为多列,每列的最大长度为 5?

最佳答案

像这样

#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("");
}
}

关于C:以多列形式写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43357429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com