c - 如何读取长度未知、没有空格的矩阵?

标签 c arrays matrix scanf

我的输入文件如下所示:

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/

相关文章:

比较两个大文件的所有元素

c - 静态变量不在函数中保留它们的值

Matlab错误: Index exceeds matrix dimensions (Looking a single element of a vector only)

c# - C# 中的链接二维矩阵

c++ - |9|错误 : invalid use of non-static data member 'Matrix::row' |9|error: array bound is not an integer constant before ']' token|

c - 整数乘积溢出

c - 在另一台 PC 上运行 C Built .exe

PHP array_unique 没有索引

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

arrays - 在 Rust 中初始化字符串数组