将fgets与用户输入进行比较

时间:2010-12-04 07:22:19

标签: strcmp

你能用我的代码帮我吗?我想做一个程序,确定学生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();
}

1 个答案:

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