我的输入文件如下所示:
1,12,5,14,0
4,6,2,3,24
1,2,3,4,5
每行的长度相同,但未指定有多少行以及多长。 (最大尺寸为20*20)。
我需要将它们读入一个 20*20 的数组中,这样如果该行只有 2 个数字长,则数组的其余部分为空。
我该如何做到这一点,同时省略 ,
字符以及当文件中出现换行符时从数组的下一行开始?
这是我的尝试:
int matrix[20][20];
for (int i=0; i<19; i++){
for (int j=0; j<19; j++){
fscanf(be, "%d,", &matrix[i][j]);
}
fscanf(be, "\n");
}
Ps:我只能使用 <stdio.h>
和 <stdlib.h>
。
最佳答案
我有这个想法。下面的代码为每个循环周期从文件中读取一行并扫描它(如果它不是空行)。使用函数(在代码中实现)mystrchr
SEP
#include <stdio.h>
#include <stdlib.h>
char * mystrchr(const char * s, char x);
char * mystrchr(const char * s, char x)
{
while(*s!=0 && *s!=x) s++;
return ((!*s)?NULL:(char *)s);
}
int main(void)
{
#define FILENAME "x.txt"
#define ROWS 20
#define MAXEL 20
#define BDIM 10240
#define SEP ','
int x[ROWS][MAXEL],elr[ROWS], ronum=0,elnum,i,j;
FILE * fptr;
char buffer[BDIM],* app;
/* --- Init the array --- */
for(i=0;i<ROWS; i++)
for(j=0;j<MAXEL; j++)
x[i][j]=0;
/* --- Open the file --- */
fptr=fopen(FILENAME,"r");
if (!fptr)
return 1;
/* --- Gets data from file --- */
while(ronum<ROWS && fgets(buffer,BDIM,fptr)) {
app = buffer;
/* Takes only non-void lines */
if (*app && *app!='\n' && *app!='\r') {
elnum=0;--app;
/* Scan the line */
do {
if (* ++app ) {
x[ronum][elnum++]=strtol(app,NULL,0);
}
app = mystrchr(app,SEP);
} while(app && elnum<MAXEL);
// -- save the number of element per row
if (elnum) {
elr[ronum]=elnum;
ronum++;
}
}
}
if (fptr)
fclose(fptr);
/* --- Prints data --- */
for(i=0;i<ronum;i++) {
for(j=0;j<elr[i];j++) {
printf("%d ",x[i][j]);
}
puts("");
}
return 0;
}
关于c - 如何读取长度未知、没有空格的矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59068945/