Scanf makes the loop end earlier
c='q';
while(c=='q')
{
printf("hello");
scanf("%c",&c);
}
Why does the loop exit for no reason when entering data?
I'm going to assume that you want user input to 'q'
mean quit, and you want the loop to end when c == 'q'
.
Try:
c='\0';
while(c !='q')
{
printf("hello");
scanf("%c",&c);
}
The loop doesn't go out without a reason. The call scanf
will read the character from stdin
and store it in c
, thereby changing the value c
. When the loop condition is checked, presumably c
not anymore ==
'q'
(for example, you typed something other than "q").
If you try to loop until the user types "q":
do {
printf("hello");
scanf("%c", &c);
}
while (c != 'q');
But note that on most console systems scanf
it will not return until the user has typed in a full line of text and pressed enter. If you want to do keyword input, you probably want to look at a different function.