我们可以在 else 中使用 scanf() 函数吗,就像我在这段代码中使用的那样。 因为我无法为性别变量输入值(字符)。 所以我想知道为什么我无法输入性别变量的值?
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int age;
char s,ms;
printf("Please enter M if you are married or U if you are un-married\n");
scanf("%c", &ms);
if(ms=='M')
printf("\nyou are recruted");
else if(ms=='U')
{
printf("\nenter sex- A for male & B for female\n");
scanf("%c",&s);
if(s=='A')
{
printf("\nEnter your age\n");
scanf("%d",age);
if(age>30)
printf("\nYou are selected");
else
printf("\nYour age is less for this job");
}
else if(s=='B')
{
printf("\nEnter your age\n");
scanf("%d",age);
if(age>25)
printf("\nyou are recruted");
else
printf("\nyour age is less to be recruted");
}
else
{
printf("Please enter A for male or B for female");
}
}
else
{
printf("PLEASE ENTER THE CORRECT VALUE\n please enter M for Married or U for un-married");
}
getch();
}
输出:
Please enter M if you are married or U if you are un-married
U
enter sex A for male or B for female
Please enter A for male or B for female
最佳答案
当您在第一次读取此 scanf 时输入数据时:
scanf("%c", &ms);
换行符保留在键盘中。要解决这个问题,请在您的第二个 scanf 中添加一个空格:
scanf(" %c",&s);
这是在 scanf< 之前消耗
读取用户输入。另请注意,您错过了 stdin
中可能由先前用户输入(如 carriage return
)留下的任何尾随字符scanf("%d",age);
中的 &
:
另请注意 main
should return int
.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age;
char s,ms;
printf("Please enter M if you are married or U if you are un-married\n");
scanf("%c", &ms);
if(ms=='M')
printf("\nyou are recruted");
else if(ms=='U')
{
printf("\nenter sex- A for male & B for female\n");
scanf(" %c",&s);
if(s=='A')
{
printf("\nEnter your age\n");
scanf("%d",&age);
if(age>30)
printf("\nYou are selected");
else
printf("\nYour age is less for this job");
}
else if(s=='B')
{
printf("\nEnter your age\n");
scanf("%d",&age);
if(age>25)
printf("\nyou are recruted");
else
printf("\nyour age is less to be recruted");
}
else
{
printf("Please enter A for male or B for female");
}
}
else
{
printf("PLEASE ENTER THE CORRECT VALUE\n please enter M for Married or U for un-married");
}
getchar();
return 0;
}
阅读Why is adding a leading space in a scanf format string recommended?
关于c - 我无法在 else 语句中使用 scanf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28322838/