连续的scanf,第二个不要求用户输入第二个输入

3
当我运行代码时,它确实要求我输入年龄。但是没有要求输入性别?这个代码有什么问题。
#include<stdio.h>
#include<conio.h>
int main(void)
{
    int age;
    char sex;

    printf("Enter your age \n");
    scanf("%d",&age);
    printf("Your age is %d \n",age);

    printf("Enter your sex \n");                 
    scanf("%c",&sex);
    printf("Your sex is %c \n",sex);
    getch();
    return 0;
}

1
之前输入了换行符。 - BLUEPIXY
你需要检查scanf()的返回值:if (scanf(...) != N) /* error */; 其中N是预期分配的数量。 - pmg
3个回答

5

在扫描age时,您留下了一个尾随的换行符,这被认为是后续scanf()使用%c格式说明符所需的有效且充分的输入。请更改此问题。

 scanf("%d",&age);

to

scanf("%d%*c",&age);

为了吃掉尾随的换行符。


话虽如此,getch()不是标准C函数。你应该使用stdio.h中的getchar()代替。


1
细节:scanf("%d%*c",&age);会“吃掉”紧随age之后的字符,无论是'\n'还是其他任何字符。 - chux - Reinstate Monica

4

由于上一个scanf()函数留下了一个尾随的换行符\n,因此请尝试:

scanf(" %c",&sex);

注意在%c之前的空格。该空格会消耗掉未被处理的末尾换行符\n


-1
#include<stdio.h>
#include<conio.h>
int main(void)
{
    int age;
    char sex;

    printf("Enter your age \n");
    scanf("%d",&age);
    printf("Your age is %d \n",age);
    fflush(stdin);     // Library function to clean the buffer..
    printf("Enter your sex \n");                 
    scanf("%c",&sex);
    printf("Your sex is %c \n",sex);
    getch();
    return 0;

}


1
fflush(stdin);会在某些系统上清除缓冲区stdin,但这是C规范中未定义的行为,不是可移植的解决方案。 - chux - Reinstate Monica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接