将 fgets 与用户输入进行比较
你能帮我修改我的代码吗?我想做一个程序来确定学生 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();
}
can you help me with my code? I want to do a program that will determine if the student id was already used, i can compare them once... but what i want to do is to have a comparison every time the user inputs another student id so... the program will know if the user inputs another used id, i know i need to have a loop before the "Enter student id:".. but still having a hard time to think for the conditions, or if you have a better solutions... i would be happy using it..
guys this is my code:
#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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议使用 goto 函数...它解决了问题,但我有点担心,因为可能有一个我还没有遇到的错误,这是我的新代码:
任何其他更好的解决方案,thnx ^_^
i was advice to use goto function... and it solve the problem but i was kinda worried because there might have a bug i haven't encountered yet, this is my new code:
any other better solutions thnx ^_^