gpt4 book ai didi

c - 构建结构阵列问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:04 25 4
gpt4 key购买 nike

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

我读取的文件格式如下

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com