如何使用文件填充结构(下面附有的代码)?

How to Populate the structure using a file(code attached below)?

本文关键字:代码 文件 何使用 填充 结构      更新时间:2023-10-16

我正在尝试使用底部给出的文件填充结构,请在代码中建议进行一些编辑,以便我可以打印结构,因为我在main((函数中尝试过,这是我第一次在stackoverflow上,所以请原谅我在发布此问题时犯的一些错误。

文件内容一个接一个,它们是声明结构的顺序(可变位置相同(

请指导我正确填充结构并在main((函数中打印它。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
//this code works on ZERO INDEXING
struct Empdetails
{
char name[25];
char id[8];
char password[4];
int casual;
int medical;
int earned;
} emp[5];//declaring array of structures
/*I am trying to convert the file to a structure and then use the 
structure to access the data and 
I'm also using files to store the information*/
extern void table()
{
FILE *fp;//definig a file pointer
char ch;
char  line[4096];
char *token;//token pointer that points to a 
int tokenposition=0;//token here means the particular text separated by comma
int lineposition=0;//line here is the entire line which has entire details of the an emmployee 
fp=fopen("emplyoyeeinfo.txt","r");//opening the file and reading it
while(fgets(line,4096,fp) !=NULL) //accessing the lines one by one and using a n to recognize the end of a line
{
tokenposition=0;//when we tokenize the line we need the count to keep a track of where we are int he string
//printf("%s n",line);//used to check which line is not being read by the compiler
token = strtok(line,",");//this seperates a line into token(entity) based on a delimiter,here the delimiter is a comma
//string tokenization` 
while(token != NULL)
{
switch(tokenposition)//acessing the required element through the tokenposition counter
{
case 0:
strcpy(emp[lineposition].name,token);
break;
case 1:
strcpy(emp[lineposition].id,token);
break;
case 2:
strcpy(emp[lineposition].password,token);
break;
case 3:
emp[lineposition].casual=atoi(token);
break;
case 4:
emp[lineposition].medical=atoi(token);
break;
case 5:
emp[lineposition].earned=atoi(token);
break;
}
token =strtok(NULL,",");
tokenposition++;//to access the next token in the same line
}
lineposition++;//after all the tokens are put in a structure,wwe move to the next line and redo the entire process
}    
}
void main()
{
int i;
for (i = 0; i < 5; i++)
{
printf("33[34mnntNAME : %s33[0mn", emp[i].name);
printf("33[34mnntID : %s33[0mn", emp[i].id);
printf("33[34mnntPASSWORD : %d33[0mn", emp[i].password);
printf("33[34mnntCASUAL : %f33[0mn", emp[i].casual);
printf("33[34mnntMEDICAL : %c33[0mn", emp[i].medical);
printf("33[34mnntEARNED : %s33[0mn", emp[i].earned);
}
}

文件是(姓名,用户ID,密码,临时假,病假,挣假(

Ramesh,QW120345,PO56,10,15,7
Rajesh,QW120905,IO56,10,15,7
Kajal,JI456987,IWQ9,10,15,7
Harleen,HJ782013,ZM12,10,15,7
Jim,BN784569,KL45,10,15,7

尝试打印结构时的代码输出在屏幕截图中

两件事:

  1. 在尝试打印结构的内容之前,您需要从main()实际调用table()函数以调用它。否则,结构(以及 C 中的任何其他变量(最初由垃圾值填充。
  2. main()中的printf()语句未使用正确的格式说明符来匹配Empdeials结构中定义的变量类型。确保使用正确的说明符(有关说明符的更多信息,请参阅此页面:http://www.cplusplus.com/reference/cstdio/printf/(