2010-12-04 74 views
0

你能帮助我解决我的问题吗?我想做一个程序,以确定是否已经使用学生ID,我可以比较一次......但我想要做的是每次用户输入另一个学生ID时进行比较以便...程序将知道如果用户输入另一个使用的ID,我知道我需要在“输入学生ID:”之前有一个循环,但仍然很难考虑条件,或者如果你有更好的解决方案...我会使用它,就会快乐.. 的家伙,这是我的代码:将fgets与用户输入进行比较

#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

我是建议使用goto功能...它解决了问题,但我有点担心,因为有可能有一个bug我的避风港还没有遇到,这是我的新代码:

#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^_^

相关问题