Scanf需要的值多于C中的值

时间:2014-04-06 16:07:15

标签: c struct scanf

我正在尝试学习结构,并且我正在使用此代码

#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("%d\n",i);
        printf("%s\n",student[i].name);
        printf("%s\n",student[i].am);
        printf("%d\n",student[i].semester);
    }

    system("pause");
}
void read_struct(struct elements p[])
{

    gets(student[i].name);
    gets(student[i].am);
    scanf("%d\n",&student[i].semester);
}

我面临以下问题: 在第二次迭代期间,当我输入变量student[1].semester的值时,程序不会打印我输入的内容,但它等待我输入另一个数字,按回车键然后打印。我在每次获取和scanf之后尝试fflush(stdin),我遇到了同样的问题。

2 个答案:

答案 0 :(得分:4)

尝试替换

scanf("%d\n", &student[i].semester);

scanf("%d", &student[i].semester);

除此之外,fflush(stdin)调用未定义的行为,因此不要使用它。

答案 1 :(得分:1)

您的代码在如此多的级别上都是错误的。而不只是添加一个评论指出他们,我会告诉你一个更正确的&#34;方式:

#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("%ld\n", i);
        printf("%s\n", students[i].name);
        printf("%s\n", students[i].am);
        printf("%d\n", 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] = '\0';
    if (p->am[strlen(p->am) - 1] == '\n')
        p->am[strlen(p->am) - 1] = '\0';
}

尾随空格不起作用的原因是因为scanf函数将继续读取输入,直到它看到非空白的东西。在这种情况下,在您输入最后一个数据后,scanf仍然想要读取并丢弃所有空格,它不知道用户不应该再输入任何输入。

你必须手动阅读和跳过尾随空格,就像我上面的程序一样。