【问题标题】:Convert data from file into an array of integers (C)将文件中的数据转换为整数数组 (C)
【发布时间】:2020-04-12 20:16:25
【问题描述】:

我在 txt 中有以下数据。我想将第 4 列的每个数字提取到一个没有重复数字的数组中

[1] [0] 1   50
[1] [2] 1   6

[1] [13]    4   8-35-38

输出应该是这样的:[50,6,8,35,38]

如何将它们存储到数组中?

【问题讨论】:

  • 假设您不是要在示例数组中写入 6 两次?
  • @Jake 他们肯定是 36 岁。
  • @Cipher 您可以使用 fgets 读取每个文件行,然后使用 sscanf 解析它们或使用指针扫描字符串。最后,将找到的每个数字添加到数组中,检查重复项并将其插入,以便始终对数组进行排序。

标签: c arrays text duplicates


【解决方案1】:

以下是我的想法,希望对你有所帮助。

您可以使用此文件中的 fgets 信息

char line[256];
int first, second, third;
char forth[256];
while (fgets(line, sizeof(line), file)) {
    printf("%s", line); 
    sscanf(line, "[%d] [%d] %d   %s\n", &first, &second, &third, forth)
}

然后使用strtokatoi(将字符串转换为int,也可以使用strtolsscanf)函数获取每一行的所有数字。

char* token = strtok(line, "-"); 

    while (token != NULL) { 
        int i = atoi(token)
        token = strtok(NULL, "-"); 
    } 

i 值复制到一个数组中。

然后创建一个消除重复号码的函数,例如:

uint32_t delete_duplicate_value (uint32_t * list, uint32_t size) {
    for (uint32_t i = 0; i < size; i++) {
        for (uint32_t j = i+1; j < size; j++) {
            if (list[i] == list[j]) {
                for (uint32_t k = j; k < size; k++) {
                    list[k] = list[k + 1];
                }
                size--;
                j--;
            }
        }
    }
    return size;
}

【讨论】:

  • i 跳过一些值是什么意思
猜你喜欢
  • 1970-01-01
  • 2016-02-27
  • 2011-08-13
  • 1970-01-01
  • 2020-07-23
  • 2018-10-07
  • 1970-01-01
  • 2016-04-15
  • 2015-01-27
相关资源
最近更新 更多