【问题标题】:Reading different kind of variables of unknown quantity from a .txt file line by line从 .txt 文件中逐行读取不同种类的未知数量变量
【发布时间】:2017-03-31 02:08:59
【问题描述】:

我需要从 .txt 文件中读取一个整数、一个字符串,然后是未知数量的整数。这应该逐行完成。

.txt 文件示例:

541 Andy  76 55 84 80
841 Kevin 51 37 60 55 71 68
418 Erik 25 85 40
966 Martha  64 82 71 83 55

输出应该是这样的:

ID:541 Name:Andy Values: [76, 55, 84, 80]
ID:841 Name:Kevin Values: [51, 37, 60, 55, 71, 68]
ID:418 Name:Erik Values: [25, 85, 40]
ID:966 Name:Martha Values: [64, 82, 71, 83, 55]

问题是,我不知道一个人有多少值。所以我的代码应该不断将新整数添加到数组中,直到它看到行尾。我必须在之后将这些信息传递给函数这个。所以仅仅将这些打印到屏幕上是不够的。我应该能够访问和使用它们。而且我不能扫描所有的 .txt 文件(所以不能使用 fscanf),因为我需要将它们传递给函数人员按人。

【问题讨论】:

  • 使用malloc()动态分配数组。如果行中有更多数字,请使用realloc() 增加其大小。循环执行此操作。
  • @LưuVĩnhPhúc 那里的答案对字数有硬编码限制。不是一个好模仿的设计。
  • @Barmar 您不需要硬编码,只需继续拆分令牌,直到行中没有令牌
  • @LưuVĩnhPhúc 但他需要将所有数字放入一个数组中。

标签: c


【解决方案1】:

我先定义一个Person 结构

struct Person {
    int id;
    char *name;
    int *nums;
    size_t nums_size;
};

还有一组Persons。

#define BUFFER_SIZE 128
struct Person *persons;
int persons_index = 0;
size_t persons_size = BUFFER_SIZE;
persons = malloc(persons_size * sizeof(struct Person));

在循环中,使用 fgetc 一次读取一个字符,直到在类 Unix 系统上通常遇到换行符 \n。请注意,您应该始终检查缓冲区溢出并根据需要扩展缓冲区。

char *buffer;
int buffer_index = 0;
size_t buffer_size = BUFFER_SIZE;
buffer = malloc(buffer_size * sizeof(char));
while ((c = fgetc(file)) != EOF) {
    if (buffer_index > buffer_size - 2) {
        buffer_size *= 2;
        buffer = realloc(buffer, buffer_size);
    }

    if (c == '\n') {
        /* Tokenize here */
    } else {
        /* Store the character and null terminate the buffer */
    }
}

假设缓冲区中有整行,使用strtok 标记该行。使用atoi 转换每个字符串整数。人名后面的值转换基本同上。

int nums_index = 0;
size_t nums_size = BUFFER_SIZE;
persons[persons_index].nums = malloc(nums_size * sizeof(int));
/* Assuming strtok has been called before for person's id and name */
while ((token = strtok(NULL, " ")) != NULL) {
    if (nums_index > nums_size - 1) {
        nums_size *= 2;
        persons[persons_index].nums = realloc(
            persons[persons_index].nums, nums_size);
    }
    persons[persons_index].nums[nums_index] = atoi(token);
    nums_index++;
}
persons[persons_index].nums_size = nums_index;

别忘了free缓冲区和persons数组,请注意我留下了很多细节和错误检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 2022-12-15
    • 2021-10-18
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多