【问题标题】:Simple read/display C program outputs incorrect value while user inputs data简单的读取/显示 C 程序在用户输入数据时输出不正确的值
【发布时间】:2017-09-22 20:44:08
【问题描述】:

有人可以在您的 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;

}

当我们输入年龄并按回车键时,它会滑倒并显示错误的输出,而没有晚上要求第三个输入“你是男性还是女性?”。我在 Turbo C++、Dev C++、Code Blocks 上测试过,都显示相同的错误输出。

【问题讨论】:

标签: c scanf


【解决方案1】:

您的问题是 scanf("%c", &amp;s); 采用换行符。也许你可以尝试下面的scanf(" %c", &amp;s);(重要的是%c之前的空白),如此处所述Problems with character input using scanf()How to do scanf for single char in C

【讨论】:

    【解决方案2】:

    这样写就对了

    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

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      相关资源
      最近更新 更多