Reputation: 518
Help me Please. I want to know why it happen.
This code is not give right answer:
#include < stdio.h>
int main()
{
char c,ch;
int i;
printf("Welcome buddy!\n\nPlease input first character of your name: ");
scanf("%c",&c);
printf("\nPlease input first character of your lovers name: ");
scanf("%c",&ch);
printf("\nHow many children do you want? ");
scanf("%d",&i);
printf("\n\n%c loves %c and %c want %d children",c,ch,c,i);
return 0;
}
but this code give right answer.
#include < stdio.h>
int main()
{
char c,ch;
int i;
printf("Welcome buddy!\n\nPlease input first character of your name: ");
scanf(" %c",&c);
printf("\nPlease input first character of your lovers name: ");
scanf(" %c",&ch);
printf("\nHow many children do you want? ");
scanf("%d",&i);
printf("\n\n%c loves %c and %c want %d children",c,ch,c,i);
return 0;
}
Why? and How?
Please help me anyone who know this why it happend.
Upvotes: 2
Views: 22169
Reputation: 320
your scanf() function takes input from stdin. Now when you hit any character from keyboard and hit enter, character entered by you is scanned by scanf() but still enter is present in stdin which will be scanned by scanf() below it. To ignore white spaces you have to use scanf() with " %c".
Upvotes: 0
Reputation: 859
The scanf function reads data from standard input stream stdin.
int scanf(const char *format, …); The white-space characters in format, such as blanks and new-line characters, causes scanf to read, but not store, all consecutive white-space characters in the input up to the next character that is not a white-space character.
Now, when you press, by example, "a" and "return", you have two chars in the stdin stream: a and the \n char. That is why the second call to scanf assign the \n char to ch var.
Upvotes: 0
Reputation: 551
The first program doesn't work properly, because the scanf function when checking for input doesn't remove automatically whitespaces when trying to parse characters.
So in the first program the value of c
will be a char and the value of ch
will be the '\n'
(newline) char.
Using scanf("\n%c", &varname);
or scanf(" %c", &varname);
will parse the newline inserted while pressing enter.
Upvotes: 2
Reputation: 4041
While you are giving like this, It will not ignore the white spaces.
scanf("%c",&ch);
When you are giving the input to the first scanf
then you will give the enter('\n')
. It is one character so it will take that as input to the second scanf
. So second input will not get input from the user.
scanf(" %c",&ch);
If you give like this, then it will ignore that white space character, then it will ask for the input from the user.
Upvotes: 6