我試圖讀取文件,將特定的標記放入結構中並讀取它們。構建結構陣列的問題
文件即時閱讀的格式如下
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�� �
任何人都知道所有這些額外的字符?我的朋友說,「問題是你試圖以同一確切結構存儲文件每一行的值。」但我並不真正瞭解他。這就是我想要做的,將它添加到結構數組中。
我使用的strtok獲得名稱,所以我相信令牌是NULL終止 – Jovis13