关于C中的结构

时间:2017-02-11 14:48:05

标签: c

如果我尝试运行此代码,那么它不会问我s2.name的值。为什么会这样?

#include<stdio.h>

int main()
{
    struct student
    {
         char name;
         int roll;
         int age;
    };

    struct student s1;
    struct student s2;

    printf("Enter name of the student: ");
    scanf("%c", &s1.name);
    printf("%c", s1.name);
    printf("\n");

    printf("Enter name of the student: ");
    scanf("%c", &s2.name);
    printf("%c", s2.name);

    return 0;
}

2 个答案:

答案 0 :(得分:2)

输入单个字符并按 Enter 键时,实际上是在输入两个字符:输入中的字符和中的换行符输入 key。

第二个scanf读取此换行符。

或者,如果您将多个字符作为第一个名称的输入,则第二个字符将由第二个scanf读取。

解决第一个问题的方法很简单:通过在格式前面添加一个空格,告诉scanf读取并丢弃前导空白区域(换行符),像

scanf(" %c", &s2.name);
//     ^
// Note space here

解决第二个问题的方法是改为读取字符串,这意味着您必须将name成员转换为数组,然后使用"%s"格式(最好具有指定的宽度,因此您不会读取多个字符。)

答案 1 :(得分:0)

您基本上输入两个字符:   - 你输入的那个   - 换行符'\ n`,因为你点击了`enter` 解决这个问题的方法是在读取第一个“名称”后清除标准输入:

#include<stdio.h>

int main()
{
    struct student
    {
         char name;
         int roll;
         int age;
    };

    struct student s1;
    struct student s2;

    printf("Enter name of the student: ");
    scanf("%c", &s1.name);
    printf("%c", s1.name);
    printf("\n");
    fflush(stdin); //only works on windows, clears the input buffer
    printf("Enter name of the student: ");
    scanf("%c", &s2.name);
    printf("%c", s2.name);

    return 0;
}

清除输入缓冲区的另一种方法是:

while (getchar() != '\n');

这将读入输入缓冲区中的所有字符,因为只要getchar()scanf()等函数读取输入,输入就会从stdin中删除。
修改
当您使用getchar()scanf()等输入值时,您输入stdin的符号(大多数情况下通过键盘)首先存储在输入缓冲区中(标准输入)。 getchar()或任何类似的函数然后从输入缓冲区中取出它应该读入的值。例如:

scanf("%d", &var);
scanf("%d", &var2);

如果我输入5x,输入缓冲区中的字符为'5', 'x'\n(因为您点击了enter键)。然后,第一个scanf()取出'5',因为它符合格式字符串%d。之后,输入缓冲区中的字符为'x'\n。在这种情况下,scanf会返回1,因为它会正确读入一个值 当它继续到第二个时,scanf()甚至不会让你输入任何东西,因为输入缓冲区stdin中已经有了东西。但是,它不会存储任何数据,因为stdin中的第一个“项目”是'x'。这不符合格式字符串%d。然后编译器不会继续读取。在这种情况下,scanf会返回0,因为没有正确读取值。