有人可以在您的IDE上运行以下C程序并告诉我我缺少什么吗?。
#include<stdio.h>
#include<conio.h>
int main()
{
int a;
char s;
char n[10];
printf("What is your name?: ");
scanf("%s", &n);
printf("What is your age?: ");
scanf("%d", &a);
printf("Are you male or female?: ");
scanf("%c", &s);
printf("Your name is %s\nYour age is %d\nYour sex is %c\n", n, a, s);
getch();
return 0;
}
当我们进入年龄并点击输入按钮时,它会滑动并显示错误的输出而没有晚上要求第三个输入&#34;你是男性还是女性?&#34;。我在Turbo C ++,Dev C ++,Code Blocks上测试它,都显示相同的错误输出。
答案 0 :(得分:3)
您的问题是scanf("%c", &s);
采用换行符。也许您可以尝试以下scanf(" %c", &s);
(重要的是%c
之前的空格),如此处所述Problems with character input using scanf()或How to do scanf for single char in C
答案 1 :(得分:0)
编写
是正确的printf("What is your name?: ");
scanf("%s", n);
^^^
甚至
printf("What is your name?: ");
scanf("%9s", n);
而不是
printf("What is your name?: ");
scanf("%s", &n);
和
printf("Are you male or female?: ");
scanf(" %c", &s);
^^^
而不是
printf("Are you male or female?: ");
scanf("%c", &s);
否则在最后一种情况下,空格字符将被读入变量s
。