I am new to c language, and I tried this code below, but it seems scanf has been skipped, when I run this code, it only asked me enter name and age and skipped the lines bel
This happens because blankspace is also treated as a character and and happens when you press enter. So Leave a space.
scanf("(space)%c",&something);
Change
scanf("%c", &sex);
to
scanf(" %c", &sex);
^
space
and
scanf("%c", &status);
to
scanf(" %c", &status);
^
space
The problem is because of trailing newline characters after your second call to scanf()
. Since it is of %d
type specifier, when you press Enter A newline character ( '\n'
) is left in the stream and the next scanf()
tries to read that newline character, and thus, it seems as though it just skipped input, but in fact, it read the newline character.
So, the newline character is stored in the variable sex
, and thus, it skips asking you for input for that variable.
You can do the following for all scanf
s.
scanf("%c\n",&smth);
And then enter the values one by one separating them by newlines (press Enter).
This helped me too when I had the same problem.
scanf("%c*",&smth);
That makes scanf
skip any other characters that a user might input, including newlines.
Note: use appropriate format strings for each type (%s
for strings, %d
for integers, etc).
Change your code to
#include<stdio.h>
int main()
{
int age;
char sex;
char name[20];
char status;
printf("Enter your last name\n");
// scanf("%s", &name);
fgets(name,20,stdin);
printf("Enter your age\n");
scanf("%d", &age);
printf("Enter sex (M/F)\n");
scanf(" %c", &sex);
printf("your status,married, single,irrelevant (M/S/I)\n");
scanf(" %c", &status);
if(age>=16 && sex=='M')
printf("hello, Mr %s\n", name);
if(age<16 && sex =='M')
printf("hello, Master %s\n", name);
if(sex=='F' && status=='M')
printf("hello, Mrs %s\n", name);
if(sex=='F' &&(status=='S' ||status=='I'))
printf("hello,miss %s\n", name);
return 0;
}
Here, I have added an extra space before the format specifier %c
, to accommodate any previous input like newline (\n).
Another alternative method is to use getchar()
immediately before you take any character input.
Also, if you perform string input with scanf
, it will not read the input after encountering a whitespace. So, instead use fgets
for taking any string input which might contain spaces.
Another thing I changed in your code (trivial) is int main()
and return 0
.
Unless you are interested in whitespace like newlines, do not use %c
. Simply use the string conversion %s
and use the first character of the input.
Rationale: All scanf
conversion specifiers except %c
ignore white space including newlines. They are designed to read sequences of input tokens (numbers, words) where the amount and nature of white space is irrelevant. The words can all be on the same line, or each word on a different line; scanf
wouldn't care unless you force single character reads with %c
which is almost never necessary.