I cannot find out the error in the program.
Code:
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
struct stu {
char *sno;
char *sname;
char *sex;
};
void main() {
FILE *fp;
stu stus[100];
char str[15];
int i = 0;
if((fp = fopen("d:\\student.txt","rt+")) == NULL) {
printf("Cannot open the file!");
exit(1);
} else {
while(fgets(str,20,fp) !=NULL)
{
stus[i].sno = strtok(str,",");
stus[i].sname = strtok( NULL, "," );
stus[i].ssex = strtok( NULL, "," );
printf("%s %s %s\n", stus[i].sno,stus[i].sname,stus[i].ssex);
i++;
}
for(int j = 0; j < i; j++) {
printf(" %s %s %s \n", stus[j].sno,stus[j].sname,stus[j].ssex);
}
}
}
IF the data of student.txt is :
1,Jim,boy
2,Bruce,boy
3,Sala,girl
and run the program,why it shows this?
1,Jim,boy
2,Bruce,boy
3,Sala,girl
3,Sala,girl
3,Sala,girl
3,Sala,girl
Could you help me? Thank you!!My English just so so.