简单读取/显示C程序在用户输入数据时输出错误值

时间:2017-09-22 20:44:09

标签: c scanf

有人可以在您的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上测试它,都显示相同的错误输出。

enter image description here

2 个答案:

答案 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