【问题标题】:Spilt a string of integers based on delimiter and convert to int type?根据分隔符拆分一串整数并转换为int类型?
【发布时间】:2016-03-30 04:39:55
【问题描述】:

我正在编写一个程序,该程序将有序数字对文件作为输入,我想拆分这些有序对并将它们转换为整数以存储在数组中。

文件可能是这样的:

0 1
1 4
9 11
12 45

我想写一个函数,接收该行,(假设在程序的另一部分已经以空终止),在空间分割数字,然后将它们存储在一个大小为 2 的整数数组中:

 int *store = malloc(2 * sizeof(store));

我已经研究过strtok,但我是否正确地说它不是线程安全的,因此在这种情况下不是最佳选择?此外,它不会将数字转换为整数,这是函数也需要具备的。

我该如何解决这个问题?

【问题讨论】:

  • 你在使用线程吗? strtok 应该没问题。还有将字符串转换为整数的函数,请参阅atoi。
  • 可以使用strtok的线程安全伙伴:strtok_r()
  • int *store = malloc(2 * sizeof(store)); → int *store = malloc(2 * sizeof(*store));
  • 也许这个:while(fscanf(fp, "%d %d", &store[0], &store[1]) == 2) printf("%d %d\n", store[0], store[1]);?
  • 这也是 strtol(尤其是 endptr 参数)旨在帮助您解决的确切类型问题。读取每一行的简单循环,设置指向该行的指针(例如p)并使用endptr(例如ep)将每个int转换为strtol (p, &ep, 10);并更新p = ++ep;直到设置errno将读取/每行转换任意数量的整数。但是,如果您可以保证,那么每行将有精确的2 ints,fscanf 可能是最简单的(或fgets 和sscanf)。不要忘记验证所有函数的返回。

标签: c arrays token tokenize


【解决方案1】:

如果您想将未知数量的有序对读入有序对数组,有多种方法可以解决此问题。如评论中所述,如果您可以保证每行始终有 2 个整数,那么读取/将值转换为整数的最简单方法可能是使用 fscanf

(当您在每一行上具有完全相同的数据格式时,我会推荐fscanf 而不是fgets 和sscanf,这是唯一次之一,然后它只是简化示例)

当您要读取的元素数量未知时,基本方案是为一些合理预期的数字对分配内存,然后根据需要分配realloc。由于您正在阅读有序对,因此您可以通过为 pointer-to-array-of-two-int 分配存储空间来简化流程。例如,您的 ordered-pairs 数组 op 声明如下:

    int (*op)[2] = NULL;

您可以为 MXLINE 对数分配存储空间:

    op = calloc (MXLINE, sizeof *op);

(您可以使用malloc 或calloc 来分配)

在分配初始内存来保存有序对后,您可以使用包含两个十进制转换说明符(例如"%d %d")的格式字符串读取每一行并让fscanf 执行转换。您必须验证 2 转换是否发生,然后将值存储在您的数组中。

保持对您添加的配对数量的持续计数,以便您在达到限制时可以realloc。一个例子如下所示。不要忘记在不再需要时释放所有内存,并通过内存检查器运行您的代码以验证您对动态分配内存的使用。

使用您的数据文件将它们放在一个简短的示例中,您可以执行以下操作。注意:程序将从命令行第一个参数给出的文件中读取(如果没有给出文件名,则默认从stdin):

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

#define MXLINE 2

int main (int argc, char **argv) {

    int i, idx = 0, mxline = MXLINE;
    int (*op)[2] = NULL;
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    /* allocate/validate initial memory */
    if (!(op = calloc (MXLINE, sizeof *op))) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        return 1;
    }

    /* read each ordered pair into 'op' array */
    while (fscanf (fp, "%d %d", &op[idx][0], &op[idx][1]) == 2) {
        if (++idx == mxline) { /* realloc when limit reached */
            void *tmp = realloc (op, sizeof *op * mxline * 2);
            if (!tmp) { /* validate reallocation */
                fprintf (stderr, "error: realloc failed.\n");
                break;
            }
            op = tmp;    /* assign reallocated pointer to op */
            mxline *= 2; /* update line allocation limit */
        }
    }

    for (i = 0; i < idx; i++) /* show ordered pairs */
        printf ("pair[%3d] %3d : %3d\n", i, op[i][0], op[i][1]);

    free (op);  /* free allocated memory */

    if (fp != stdin)    /* close file if not stdin */
        fclose (fp);

    return 0;
}

使用/输出示例

$ ./bin/array_ptr2array <dat/orderedpairs.txt
pair[  0]   0 :   1
pair[  1]   1 :   4
pair[  2]   9 :  11
pair[  3]  12 :  45

内存/错误检查

不要忘记验证您是否使用了动态分配的内存,并且您正在释放所有不再需要的内存:

$ valgrind ./bin/array_ptr2array <dat/orderedpairs.txt
==8107== Memcheck, a memory error detector
==8107== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==8107== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==8107== Command: ./bin/array_ptr2array
==8107==
pair[  0]   0 :   1
pair[  1]   1 :   4
pair[  2]   9 :  11
pair[  3]  12 :  45
==8107==
==8107== HEAP SUMMARY:
==8107==     in use at exit: 0 bytes in 0 blocks
==8107==   total heap usage: 3 allocs, 3 frees, 112 bytes allocated
==8107==
==8107== All heap blocks were freed -- no leaks are possible
==8107==
==8107== For counts of detected and suppressed errors, rerun with: -v
==8107== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)

(注意: 初始分配是针对 MXLINE (2) 对的。这样做是为了强制重新分配。在现实世界中,您需要尽量减少必须分配内存。因此,如果您认为可以有 20 对左右,请将初始分配设置为 24 或 32 对或您对将拥有的数字的最佳合理猜测(加上一对以防万一) ))

查看一下,如果您有任何问题,请告诉我。

【讨论】:

    【解决方案2】:

    也许这是一个解决方案:

    gets(str, 80, fp); // get a line
    sscanf(str, "%d %d", &store[0], &store[1]); // read numbers from that line
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 2016-02-29
      • 2019-09-19
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 2010-10-29
      相关资源
      最近更新 更多