。txt文件如下所示:
1,12,5,14,0
4,6,2,3,24
1,2,3,4,5
每行的长度相同,但是未指定,有多少行,以及多长时间。(最大尺寸为20 * 20)我需要将它们读取到20 * 20数组中,以便如果该行只有2个数字长,则该数组的其余部分为空。
我如何做到这一点,当文件中包含换行符时,不包括','-s,而从数组的下一行开始?
这是我的尝试:
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
读取未指定长度的行可以使用fgetc
来逐字符读取。对于您的情况,必须检查每个字符是否满足以下条件:
如果看到','
,就看到一个数字;
[如果看到'\n'
,则显示为数字和,则显示为一行。
您跳过每个非数字字符;
您将数字放在一个小的临时缓冲区中。看到数字后,可以使用atoi
;
如果您不被允许使用atoi
,请为您看到的每个数字使用number= number*10 + c-'0';
来执行c
。
我有这个主意。下面的代码在每个循环周期中从文件中读取一行,如果不是无效行,则对其进行扫描。分隔符SEP
使用以下函数检索(在代码中实现)mystrchr
#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;
}