我正在尝试学习结构,我正在使用此代码
#include <stdio.h>
struct elements
{
char name[50];
int semester;
char am[15];
}student[100];
void read_struct(struct elements p[]);
int i=0;
main()
{
for (i=0;i<2;i++)
{
read_struct(student);
}
for (i=0;i<2;i++)
{ printf("%dn",i);
printf("%sn",student[i].name);
printf("%sn",student[i].am);
printf("%dn",student[i].semester);
}
system("pause");
}
void read_struct(struct elements p[])
{
gets(student[i].name);
gets(student[i].am);
scanf("%dn",&student[i].semester);
}
我面临以下问题:在第二次迭代中,当我输入变量的值时,程序student[1].semester
不会打印我输入的内容,而是等待我输入另一个数字,按 Enter 然后打印。每次获取和扫描后我都尝试了fflush(stdin)
,但我遇到了同样的问题。
尝试替换
scanf("%dn", &student[i].semester);
跟
scanf("%d", &student[i].semester);
除此之外,fflush(stdin)
调用未定义的行为,所以不要使用它。
你的代码在很多层面上都是错误的。我不会只是添加注释指出它们,而是向您展示一种"更正确"的方法:
#include <stdio.h>
#include <string.h>
struct elements
{
char name[50];
int semester;
char am[15];
};
#define MAX_STUDENTS 2
void read_struct(struct elements *p);
int main(void)
{
struct elements students[MAX_STUDENTS]; /* No longer global */
for (size_t i = 0;i < MAX_STUDENTS; ++i)
read_struct(&students[i]); /* Pass pointer to single structure */
for (size_t i = 0;i < MAX_STUDENTS; ++i)
{
printf("%ldn", i);
printf("%sn", students[i].name);
printf("%sn", students[i].am);
printf("%dn", students[i].semester);
}
}
void read_struct(struct elements *p)
{
/* fgets is safe, in that it will not overwrite your buffer */
fgets(p->name, sizeof(p->name), stdin);
fgets(p->am, sizeof(p->am), stdin);
scanf("%d", &p->semester);
/* Skip trailing whitespace (like the newline) in the input buffer
* left after the `scanf` call above.
* Do it by reading one character and see if it's a newline. If it's
* not a newline, then read next character, and so on until we get
* the newline. It's safe because we *know* there is a newline in the
* input buffer after the `scanf` call above.
*/
int c;
while ((c = fgetc(stdin)) != EOF && c != 'n')
;
/* The `fgets function leaves the newline in the buffer so we
* have to remove it, if it's there.
* This is done by first checking if the last character (strlen(...) - 1)
* is a newline, and if it is then we change that newline to the string
* terminator character so the string is terminated there.
*/
if (p->name[strlen(p->name) - 1] == 'n')
p->name[strlen(p->name) - 1] = ' ';
if (p->am[strlen(p->am) - 1] == 'n')
p->am[strlen(p->am) - 1] = ' ';
}
尾随空格不起作用的原因是,scanf
函数将继续读取输入,直到看到非空格的内容。在这种情况下,在您输入最后一个数据后,scanf
仍然想要读取并丢弃所有空格,它不知道用户不应该再输入任何输入。
您真的必须手动读取并跳过尾随空格,就像我在上面的程序中所做的那样。