代码运行时无法提供字符 [英] can't feed character when code runs
问题描述
我是编程新手。我已经为下面提到的问题写了一个代码
Q.如果
条件:
1,司机已经投保了/>
2)司机未婚,男性,30岁以上
3)司机未婚,女性,25岁以上
问题我面临的是 - 进入年龄后我无法进入婚姻状态,输出屏幕看起来像这样 -
输入年龄:28
输入婚姻状况m / u输入性别m / f(当我在这里给出一个角色,程序结束)
司机没有投保
代码如下。
A.
Hi I am new to programming. I have written a code for a problem mentioned below
Q. A driver is insured if
conditions:
1)Driver is married
2)Driver is unmarried,male,above 30 yrs of age
3)Driver is unmarried,female,above 25 yrs of age
The problem I am facing is- after entering age I am not able to enter marital status, the output screen looks like this-
Enter age: 28
Enter marital status m/u Enter sex m/f ("when i give a character here the program ends")
Driver is not insured
Code is given below.
A.
#include<stdio.h>
int main()
{
int a; //variable a for age
char ms,sx; //ms for marital status, sx for sex
printf("Enter age: ");
scanf("%d",&a);
printf("Enter marital status m/u ");
scanf("%c",&ms);
printf("Enter sex m/f ");
scanf("%c",&sx);
if((ms=='m')||(a>30&&ms=='u'&&sx=='m')||(a>25&&ms=='u'&&sx=='f'))
printf("Driver is insured");
else
printf("Driver is not insured");
return 0;
}
推荐答案
从scanf
获取单个字符非常棘手(例如,参见如何在单个字符中执行scanf Cat Stack Overflow [ ^ ])。
正如那里建议的那样,你可以改成
Getting a single character fromscanf
is tricky (see, for instance "How to do scanf for single char in C" at Stack Overflow[^]).
As suggested there, you could change from
scanf(%c,& ms);
scanf("%c",&ms);
to
to
scanf(" %c",&ms);
注意%c
之前的空白。
以同样的方式,来自
Note the blank before %c
.
And in the same way, from
scanf(% c,& sx);
scanf("%c",&sx);
to
to
scanf(" %c",&sx);
这篇关于代码运行时无法提供字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!