转换数组大小

标签 c arrays algorithm multidimensional-array

以下代码从文件获取输入并将其存储在一维数组中。我想要一个矩阵类型的输入,例如:

1,2,4
3,4,5
5,6,7

(或)

2,3,4,5
4,5,6,7
7,6,5,4
3,4,5,6

其中矩阵的大小各不相同,它们以逗号分隔,存储在二维数组中。我应该对以下代码进行哪些更改?

#include <stdio.h>
#include <stdlib.h>

int main(){
    char file[51];
    int data, row, col, c, count, inc;
    int *array, capacity=50;
    char ch;
    array = (int*)malloc(sizeof(int) * capacity);
    printf("\nEnter the name of the file with its extention\n");
    scanf("%s", file);
    FILE *fp = fopen(file, "r"); 
    row = col = c = count = 0;
    while (EOF != (inc = fscanf(fp,"%d%c", &data, &ch)) && inc == 2){
        ++c; //COLUMN count
        if (capacity == count)
            array = (int*)realloc(array, sizeof(int) * (capacity *= 2));
        array[count++] = data;
        if(ch == '\n'){
            ++row;
            if (col == 0){
                col = c;
            } else if (col != c){
                fprintf(stderr, "format error of different Column of Row at %d\n", row);
                goto exit;
            }
            c = 0;
        } else if (ch != ',') {
            fprintf(stderr, "format error of different separator(%c) of Row at %d \n", ch, row);
            goto exit;
        }
    }
    {   //check print
        int i, j;
        //int (*matrix)[col] = array;
        for(i = 0; i < row; ++i){
            for(j = 0; j < col; ++j)
                printf("%d ", array[i * col + j]);//matrix[i][j]
            printf("\n");
        }
    }
exit:
    fclose(fp);
    free(array);
    return 0;
}

最佳答案

这使用 fgets 读取每一行并使用 strtol 解析一行中的整数。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>

int get_int_range ( char *line, char **next, char *term, int *value, int min, int max);
int get_int_series ( int cols, int dest[][cols], int inputrow, int min, int max, char *line, char *delim);
int get_int_count ( int min, int max, char *line, char *delim);

int main( int argc, char *argv[])
{
    char line[900] = {'\0'};
    char file[100] = {'\0'};
    int valid = 0;
    int rows = 0;
    int cols = 0;
    int eachrow = 0;
    int eachcol = 0;
    FILE *fp = NULL;

    printf ( "Enter the name of the file with it's extension\n");
    fgets ( file, sizeof ( file), stdin);
    file[strcspn ( file, "\n")] = '\0';//remove trailing newline

    if ( ( fp = fopen ( file, "r")) != NULL) {

        fgets ( line, sizeof ( line), fp);//read a line
        rows = get_int_count ( INT_MIN, INT_MAX, line, ",\n");
        rewind ( fp);
        if ( rows) {
            cols = rows;
            //once the size is obtained, the array can be declared
            int array[rows][cols];

            for(eachrow = 0; eachrow < rows; eachrow++) {
                if ( ( fgets ( line, sizeof ( line), fp)) == NULL) {//read a line
                    fclose ( fp);
                    printf ( "Problem! not enough lines in file\n");
                    return 1;
                }
                valid = get_int_series ( cols, array, eachrow, INT_MIN, INT_MAX, line, ", \n");
                if ( !valid) {
                    fclose ( fp);
                    printf ( "Problem!\n");
                    return 1;
                }
            }
            if ( ( fgets ( line, sizeof ( line), fp)) != NULL) {//read a line
                fclose ( fp);
                printf ( "Problem! too many lines in file\n");
                return 1;
            }
            for(eachrow = 0; eachrow < rows; eachrow++) {
                for(eachcol = 0; eachcol < cols; eachcol++) {
                    printf("[%d] ", array[eachrow][eachcol]);
                }
                printf("\n");
            }
            printf("\nDone\n");
        }
        fclose ( fp);
    }
    return 0;
}

int get_int_range ( char *line, char **next, char *term, int *value, int min, int max)
{
    long int input = 0;
    char *end = NULL;

    errno = 0;
    input = strtol ( line, &end, 10);//get the integer from the line
    if ( end == line) {
        printf ( "input MUST be a number\n");
        return 0;
    }
    if ( *end != '\0' && ( strchr ( term, *end) == NULL)) {
        printf ( "problem with input: [%s] \n", line);
        return 0;
    }
    if ( ( errno == ERANGE && ( input == LONG_MAX || input == LONG_MIN))
    || ( errno != 0 && input == 0)){
        perror ( "input");
        return 0;
    }
    if ( input < min || input > max) {
        printf ( "input out of range %d to %d\n", min, max);
        return 0;
    }

    if ( next != NULL) {
        *next = end;
    }
    *value = input;//set the value
    return 1;
}

int get_int_series ( int cols, int dest[][cols], int inputrow, int min, int max, char *line, char *delim)
{
    char *end = NULL;
    char *each = NULL;
    int valid = 0;
    int input = 0;
    int count = 0;
    int temp[cols];

    each = line;
    do {
        valid = get_int_range ( each, &end, delim, &input, INT_MIN, INT_MAX);
        if ( !valid) {
            printf ( "input MUST be a number\n");
            return 0;
        }
        if ( valid) {
            temp[count] = input;
            count++;
            if ( count > cols) {
                printf ( "too many integers. %d entered. only enter %d\n", count, cols);
                return 0;
            }
        }
        while ( *end && strchr ( delim, *end)) {//skip any number of delimitors
            end++;
        }
        each = end;
    } while ( end && *end);

    if ( count < cols) {
        printf ( "too few integers. need %d entered. only entered %d\n", cols, count);
        return 0;
    }
    while ( count) {
        count--;
        dest[inputrow][count] = temp[count];//set the value
    }
    return 1;
}

int get_int_count ( int min, int max, char *line, char *delim)
{
    char *end = NULL;
    char *each = NULL;
    int valid = 0;
    int input = 0;
    int count = 0;

    each = line;
    do {
        valid = get_int_range ( each, &end, delim, &input, INT_MIN, INT_MAX);
        if ( !valid) {
            return count;
        }
        if ( valid) {
            count++;
        }
        while ( *end && strchr ( delim, *end)) {//skip any number of delimitors
            end++;
        }
        each = end;
    } while ( end && *end);

    return count;
}

关于转换数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35793461/

相关文章:

c - 取消引用中的 de- 前缀是什么意思?有语言解释吗?

c++ - 如果将本地数组乘以零,为什么计时会下降?

python - 使用欧氏距离在 numpy 数组列表中查找 numpy 数组的最近邻居

arrays - 如何在VBA中将文本文件读取到数组中

遍历数组的 JavaScript 给出了错误的值

algorithm - 动态类型语言中的快速属性查找?

c++ - 如何在 map 中使用 tolower 和 lambda 函数? C++

c - 在 C 中,如何让这个程序返回数组的地址,而不是第一个元素的地址?

c - 酸测试一个http服务器

algorithm - 哪些 ML 算法或模式适合识别内容的类别和子类别?