大家好,我正在做作业,但遇到了一些问题。
这是我的变量:
struct student
{
int facN;
char name[MAX_LENGHT + 1];
char prezime[MAX_LENGHT + 1];
char familiq[MAX_LENGHT + 1];
char specialnost[MAX_LENGHT + 1];
int group;
int kurs;
};
typedef struct student BODY;
输入的函数是:
int enterBody(BODY *ps)
{
if (ps == NULL) return 0;
memset(ps, 0, sizeof(BODY));
fflush(stdin);
printf("\nFaculty No: ");
scanf("%d", &(ps->facN));
//fflush(stdin);
printf("\nName: ");
gets(ps->name);
printf("\nPrezime: ");
gets(ps->prezime);
printf("\nFamiliq: ");
gets(ps->familiq);
printf("\nSpecialnost: ");
gets(ps->specialnost);
printf("\ngrupa: ");
gets(ps->group);
printf("\kurs: ");
gets(ps->kurs);
return 1;
}
主要问题是当我运行程序时,我无法让 Prezime 和其他程序进入屏幕,然后将输入保存到变量中。
最佳答案
fflush(stdin);
会调用未定义的行为,因此您应该删除这些语句。memset()
该结构没有任何意义,因为它最终会被数据填充。- 使用
scanf("%d%*c", &var);
而不是gets()
来输入int
字段。添加%*c
以丢弃'\n'
字符。 gets()
没有缓冲区溢出保护,因此请调用fgets()
。另外,使用strcspn()
删除fgets()
写入的尾部'\n'
。- 我想你的意思是
printf("\nkurs: ");
。
精炼代码:
int enterBody(BODY *ps)
{
if (ps == NULL)
return 0;
printf("\nFaculty No: ");
scanf(" %d%*c", &ps->facN);
printf("\nName: ");
fgets(ps->name, MAX_LENGHT + 1, stdin);
(ps->name)[strcspn((ps->name), "\n")] = '\0';
printf("\nPrezime: ");
fgets(ps->prezume, MAX_LENGHT + 1, stdin);
(ps->prezume)[strcspn((ps->prezume), "\n")] = '\0';
printf("\nFamiliq: ");
fgets(ps->familiq, MAX_LENGHT + 1, stdin);
(ps->familiq)[strcspn((ps->familiq), "\n")] = '\0';
printf("\nSpecialnost: ");
fgets(ps->specialnost, MAX_LENGHT + 1, stdin);
(ps->specialnost)[strcspn((ps->specialnost), "\n")] = '\0';
printf("\ngrupa: ");
scanf(" %d%*c", &ps->group);
printf("\nkurs: ");
scanf(" %d%*c", &ps->kurs);
return 1;
}
关于无法将用户输入保存到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36749846/