#include<stdio.h>
#include<stdlib.h>
struct studentinfo{
char id[8];
char name[30];
char course[5];
}s1;
main(){
int i=0;
int count=0;
char arr[50];
FILE *stream = NULL;
stream = fopen("studentinfo.txt", "a+");
struct studentinfo *array[50];
array[i] = (struct studentinfo*) malloc(sizeof(struct studentinfo));
printf("Enter Student ID: ");
scanf("%s", array[i]->id);
fflush(stdin);
while(!feof(stream)){
fgets(arr, 6, stream);
if(strcmp(arr, array[i]->id)==0){
printf("Student ID is used!\n");
free(array[i]);
}
}
printf("Enter Student Name: ");
gets(array[i]->name);
fflush(stdin);
printf("Enter Student Course: ");
scanf("%s", array[i]->course);
fprintf(stream, "\n%s,\t%s,\t%s", array[i]->id, array[i]->name, array[i]->course);
i++;
fclose(stream);
i=0;//for freeing the space
if(array[i] != NULL){
free(array[i]);
}
getch();
}
答案 0 :(得分:0)
我是建议使用goto函数...它解决了问题,但我有点担心,因为可能有一个我还没有遇到的错误,这是我的新代码:
#include<stdio.h>
#include<stdlib.h>
struct studentinfo{
char id[8];
char name[30];
char course[5];
}s1;
main(){
int i=0;
int count=0;
char arr[50];
FILE *stream = NULL;
stream = fopen("studentinfo.txt", "a+");
struct studentinfo *array[50];
array[i] = (struct studentinfo*) malloc(sizeof(struct studentinfo));
studid:
printf("Enter Student ID: ");
scanf("%s", array[i]->id);
fflush(stdin);
while(!feof(stream)){
fgets(arr, 6, stream);
if(strcmp(arr, array[i]->id)==0){
printf("Student ID is used!\n");
goto studid;
}
}
printf("Enter Student Name: ");
gets(array[i]->name);
fflush(stdin);
printf("Enter Student Course: ");
scanf("%s", array[i]->course);
fprintf(stream, "\n%s,\t%s,\t%s", array[i]->id, array[i]->name, array[i]->course);
i++;
fclose(stream);
if(array[i] != NULL){
free(array[i]);
}
getch();
}
任何其他更好的解决方案thnx ^ _ ^