如何使用C程序[duplicate]将从文件csv读取的字符串安装到矩阵中

问题描述 投票:-1回答:1

我想将我从csv文件读取的数据安装到矩阵中。这是我的代码:

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

#define BUFSIZE 1024

int main()
{

    char *filename = "pb0.csv";

    char str[BUFSIZE];
    FILE *fpr;
    fpr = fopen(filename, "r");
    while (fgets(str, BUFSIZE, fpr) != NULL) {
        printf("%s", str);
    }

    fclose(fpr);

    return 0;
}

我的输出像:

2; 2; 1; 5; 0; 4
2; 0; 2; 1; 4; 6
2; 2; 1; 4; 6; 5
4; 4; 6; 0; 1; 3
2; 3; 1; 5; 6; 0

我想编写一个将所有数字字符串存储到矩阵中的代码,看起来像这样:

2 2 1 5 0 4
2 0 2 1 4 6
2 2 1 4 6 5
4 4 6 0 1 3
2 3 1 5 6 0

我应该写什么?任何帮助将不胜感激。

c readfile
1个回答
0
投票

只需尝试这段代码,它将使用逗号分隔的输入并返回一个矩阵

#include <stdio.h>

int main()
{


    FILE *fpr = fopen("pb0.csv", "r");

    int d;
    int counter = 0;
    while(fscanf(fpr, "%d, ", &d) != EOF){
    if(counter < 5){
        printf("%d ", d);
    }else{
        printf("%d\n", d);
        counter = 0; continue;
    }
    counter++;
    }

    fclose(fpr);

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.