0

私のコードを手伝ってもらえますか? 学生IDがすでに使用されているかどうかを判断するプログラムを実行したいのですが、それらを一度比較できます...しかし、ユーザーが別の学生IDを入力するたびに比較したいので...プログラムユーザーが別の使用済み ID を入力したかどうかがわかります。「学生 ID を入力してください:」の前にループする必要があることはわかっていますが、条件を考えるのにまだ苦労している、またはより良い解決策があるかどうか...私はそれを使って幸せになる..みんなこれは私のコードです:

#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();
}
4

1 に答える 1

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

于 2010-12-04T09:09:01.833 に答える