首页 > 解决方案 > C读取文件行到数组仅打印行中的第一个字符

问题描述

我尝试将 txt 文件中的行读取到 C 中的数组中。通过加载行的方法如下所示:

char *loadNames(FILE *file) {
    char *list = malloc(42);
    int BUFFER_SIZE = {256};
    char *buffer = malloc(BUFFER_SIZE);
    char count;

    while (fgets(buffer, BUFFER_SIZE, file)) {
        list[count] = *buffer;
        count++;
    }

    return list;
}

稍后在我的代码中,我调用该函数并打印所有值。

char *names = loadNames(file);
for (int i = 0; i < 41; i++) {
  printf("%c\n", names[i]);
}

该文件的每一行都包含一个名称。问题是当前代码只打印每个名称的第一个字符。

A
B
C

代替

Anna
Berry
Chanel

如果我在代码段#1 中打印bufferwhile 语句中的值,则会显示全名。

我该怎么做才能获得全名而不是数组中的第一个字母?

标签: c

解决方案


C 语言没有真正的字符串概念。但是标准库将字符串定义为空终止字符数组,其中char是单字符类型。所以你想要的更接近:

#define BUFFER_SIZE 256

char *loadNames(FILE *file) {
    char **list = malloc(42 * sizeof(char *));      // array of pointers
    char buffer[BUFFER_SIZE];
    char count = 0;                // never forget initialization

    while (fgets(buffer, BUFFER_SIZE, file)) {
        list[count] = strdup(buffer);          // allocate a new buffer
        count++;
    }
    list[count] = NULL;                        // sentinel value

    return list;
}

最后,您应该释放所有已分配的数组:

for(i=0; i<42; i++) {
    if (list[i] == NULL) break;         // stop at the sentinel
    free(list[i]);
}
free(list);

推荐阅读