i want to take 3 inputts from user age, gender(m/f), marital status(m/u). i used char data type for gender and marital status. here is the code below..

#include<stdio.h>
#include<conio.h>

main() {
int age;
char gender,marital_status;
printf("Enter your age: ");
scanf("%d",&age);
printf("Enter your gender (m/f): ");    
scanf("%c",&gender);
printf("\nEnter your marital status (m/u): ");      
scanf("%c",&marital_status);


}

age part works corectly, i.e it takes age from user and store it to age. But after that both below printf statements displayed at once. How to display them one by one to take input from user as gender and marital status.

有帮助吗?

解决方案

This is because %c accepts '\n' symbol that's left over from entering the age. You would be better off reading into a string, and taking the first character, like this:

char buf[2];
printf("Enter your gender (m/f): ");
scanf("%1s", buf);
gender = buf[0];
printf("\nEnter your marital status (m/u): ");
scanf("%1s", buf);
marital_status = buf[0];

The %s format specifier is set up to ignore all whitespace. Note the one character limit after % in the format specifier.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top