Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.

C#
#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;
 }
Posted
Updated 10-Aug-15 10:12am
v2
Comments
Patrice T 10-Aug-15 16:33pm    
what is your problem ?

1 solution

Getting a single character from scanf is tricky (see, for instance "How to do scanf for single char in C" at Stack Overflow[^]).

As suggested there, you could change from
Quote:
scanf("%c",&ms);
to
C
scanf(" %c",&ms);

Note the blank before %c.



And in the same way, from
Quote:
scanf("%c",&sx);
to
C
scanf(" %c",&sx);
 
Share this answer
 
Comments
Shashank1988 10-Aug-15 16:55pm    
thanks a lot...solved my problem. Adding a getchar(); after scanf() also gave the desired result...but your solution is much better. :)
CPallini 10-Aug-15 17:05pm    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900