如果我尝试运行此代码,那么它不会问我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;
}
答案 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
,因为没有正确读取值。