首页 > 解决方案 > 如何从文件C创建一个int字符串

问题描述

我有一个file.csv包含一对用逗号分隔的 int 。我的目标是从文件 ( fgets) 中读取数字并将它们char (*arr)像字符串一样放入。问题是它在逗号后添加了更多数字。我能怎么做?

例如这个号码:9514902,846 在arr:9514902,845962

主程序

#define SIZE 10
#define LEN 20


int main(){
    char (*arr)[LEN] = NULL;
    int pos = 0;
    FILE *fd = NULL;

    fd = fopen("file.csv", "r");
    arr = calloc ( SIZE, sizeof *arr);

    while ( pos < SIZE && fgets ( arr[pos], sizeof arr[pos], fd)) {
        printf ("%s", arr[pos]);
        ++pos;
    }

    fclose ( fd);
    free ( arr);

    return 0;
}

文件.csv

9514902,846
1134289,572
7070279,994
30886,48552
750704,1169
1385812,729
471548,3595
8908491,196
4915590,362
375309,212

我的输出:

9514902,845962
1134289,571587
7070279,993574
30886,485520
750704,116888
1385812,729300
471548,359462
8908491,19559
4915590,361558
375309,211958

标签: arrayscstringcharinteger

解决方案


您可以使您的代码更易于编写、维护和理解。如我所见,您也不需要动态内存分配。

改成

#define SIZE 10
#define LEN 20


int main(){
    char arr[LEN] = {0};   // just define a char array, should be sufficient.
    int pos = 0;
    FILE *fd = NULL;

    fd = fopen("file.csv", "r");
    if (!fd) {                          // don't for get the error check
        printf ("File handling error\n");
        exit (-1);
    }

    while ( pos < SIZE && fgets ( arr[pos], LEN, fd)) {
        printf ("%s", arr[pos]);
        ++pos;
    }

    fclose ( fd);
}

推荐阅读