Odd loop not working using% c

I cant programming in C. I wrote an odd loop, but it doesn't work while I use %c in scanf() .
Here is the code:

 #include<stdio.h> void main() { char another='y'; int num; while ( another =='y') { printf("Enter a number:\t"); scanf("%d", &num); printf("Sqare of %d is : %d", num, num * num); printf("\nWant to enter another number? y/n"); scanf("%c", &another); } } 

But if I use %s in this code, for example scanf("%s", &another); then it works great.
Why is this happening? Any idea?

+6
source share
4 answers

The %c conversion reads the next single character from the input, regardless of what it is. In this case, you previously read the number with %d . You had to press enter to read this number, but you did nothing to read a new line from the input stream. Therefore, when you perform the conversion of %c , it reads this new line from the input stream (without waiting for you to actually enter something, since there is already entered waiting for reading).

When you use %s , it skips any leading white space to get a character other than white. It treats the new line as white space, so it implicitly skips this pending new line. Since there is (presumably) nothing waiting to be read, he continues to wait until you enter something, as you think.

If you want to use %c for conversion, you may be preceded by a space in the format string, which also skips any empty space in the stream.

+10
source

The ENTER key lies in the stdin stream after entering the number for the first scanf% d. This key falls into the scanf% c line.

use scanf("%1s",char_array); another=char_array[0]; scanf("%1s",char_array); another=char_array[0]; .

+2
source

use getch() instead of scanf() in this case. Since scanf () expects '\ n', but you only accept one char in this scanf (). therefore, '\ n' is assigned to the next scanf (), causing confusion.

+1
source
 #include<stdio.h> void main() { char another='y'; int num; while ( another =='y') { printf("Enter a number:\t"); scanf("%d", &num); printf("Sqare of %d is : %d", num, num * num); printf("\nWant to enter another number? y/n"); getchar(); scanf("%c", &another); } } 
0
source

All Articles