문제

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