c - 构建结构阵列问题

标签 c structure

我正在尝试读取一个文件,将特定标记放入一个结构中并读取它们。

我读取的文件格式如下

Edward is enrolled in CSE 1105.
August is enrolled in CSE 1105.
SoonWon is enrolled in MATH 1426.

我的伪代码希望能帮助你理解

Open file 
send file to function create_structures to be tokenized
read file fgets(), then tokenize strtok() by delimiter space
name/course will be 1st and 5th token, add tokens to array of structures

目前的代码是

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

void create_structures(FILE* file);

struct info{
    char name[20];
    char course[4];
};

int main()
{
    FILE* fp = fopen("input-hw04b.txt","r");
    create_structures(fp);

}

voidcreate_structures(FILE* file)
{
    struct info struct_array[30]; /* Correct? want struct to be like 
                                     strcut info struct_array = {{"Edward","1105."},
                                                                 {"August","1105."}};ETC..*/
    char buffer[100];
    char* del = " ";
    char* token;
    int number,index,count;

    while(fgets(buffer,sizeof(buffer),file) != NULL)
    {
        index = 0;
        count = 0;
        token = strtok(buffer,del);
        while(token != NULL)
        {
            if(count == 0)
            {
                strcpy(struct_array[index].name,token);
            }
            if(count == 5)
            {
                strcpy(struct_array[index].course,token);
            }
            token = strtok(NULL,del);
            count = count + 1;
        }
        index = index +1;

        for (index = 0; index < count; index++)
            printf("%s %s\n", struct_array[index].name, struct_array[index].course );
    }
}

当我打印结构时,我得到以下输出

Edward 1105.

.
 �

(�n�� �
 �
�I9�� �

August 1105.

.
 �

(�n�� �
 �
�I9�� �

SoonWon 1426.

.
 �

(�n�� �
 �
�I9�� �

有人知道那些额外的字符是什么吗?我的 friend 说,“问题在于您试图以完全相同的结构存储文件每一行的值。”但我并不真正了解他。这就是我想要做的,将它添加到结构数组中。

最佳答案

你必须移动

   for (index = 0; index < count; index++)
        printf("%s %s\n", struct_array[index].name, struct_array[index].course );

在外部 while 循环之外。

还得动

index = 0;

在外层 while 循环之前。

因为现在发生的事情是您尝试将 N 个条目打印 N 次(每次您读取新行时)。但是你总是写入位置 0。

更新。内循环不应该是简单的:

while(fgets(buffer,sizeof(buffer),file) != NULL)
{
    token = strtok(buffer,del);
    strcpy(struct_array[index].name,token);
    token = strtok(buffer,del);
    strcpy(struct_array[index].course,token);
}

关于c - 构建结构阵列问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24639220/

相关文章:

将静态内核驱动程序编译为模块

c - C语言头文件的编写方法

c - 如何通过指向指针的指针访问结构成员

c++ - 栈结构数组

C - 连接函数 - 无效参数错误

c - 如何在 Contiki OS 的运行时执行不同的二进制文件?

c - 无法将二进制文件中的数据读入结构指针数组

c# - 将字节数组转换为托管结构

c - 32 位兼容模式下的 sizeof(int*)

c++ - 无法对包含字符串 C++ 的结构数组进行操作