【问题标题】:How to create a string of int from a file C如何从文件C创建一个int字符串
【发布时间】:2021-03-08 10:20:07
【问题描述】:

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

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

ma​​in.c

#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

【问题讨论】:

  • 为什么让它比需要的更复杂?如果您不介意逗号,只需将整行读入数组元素即可。
  • 在此之后我将不得不处理每个字符串。我需要正确的价值。 @SouravGhosh
  • 所以,为了清楚起见,您希望输出为 9514902,846 作为字符串,对吧?或者你想去掉逗号并连接两个 int 值?
  • 我已经尝试过你的代码,在去掉额外的 } 后,它按预期输出。你用什么编译器?
  • 这是我使用相同代码的输出:[ismail-teknimer@teknimer-fedora Karalama]$ gcc -Wall file.c [ismail-teknimer@teknimer-fedora Karalama]$ ./a.out 9514902,846 1134289,572 7070279,994 30886,48552 750704,1169 1385812,729 471548,3595 8908491,196 4915590,362 375309,212

标签: arrays c string char integer


【解决方案1】:

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

改成

#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);
}

【讨论】:

  • 我有一个包含 600 万条记录的文件。我放了一块来展示它是如何工作的。我需要动态分配它。
  • @Banana 那么你真的应该重新考虑你的策略,有 6M 记录和动态分配内存,你很可能会失败分配器函数调用。
  • char arr[SIZE][LEN],确定吗?
  • 同样,输出保持不变。 @肖恩
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 2019-12-05
相关资源
最近更新 更多