2010-12-04 143 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^_^

相關問題