I am leaning C programming. I have written an odd loop but 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 fine.
Why does this happen? Any idea?
Sometimes a user may not know about how many times a loop is to be executed. If we want to execute a loop for unknown number of times, then the concept of odd loops should be implemented. This can be done using for-loop, while-loop or do-while-loops.
If you have multiple format specifiers within the string argument of scanf, you can input multiple values. All you need to do is to separate each format specifier with a DELIMITER - a string that separates variables.
That is because there is a left over newline character in the input buffer.
On entering the loop, your second scanf will read this leftover \n from input buffer and loop runs one more time without waiting for your input and that's why you are getting Give a character line twice. A space before %c will eat up this \n (or any number of whitespaces) left behind by scanf .
The %c
conversion reads the next single character from input, regardless of what it is. In this case, you've previously read a number using %d
. You had to hit the enter key for that number to be read, but you haven't done anything to read the new-line from the input stream. Therefore, when you do the %c
conversion, it reads that new-line from the input stream (without waiting for you to actually enter anything, since there's already input waiting to be read).
When you use %s
, it skips across any leading white-space to get some character other than white-space. It treats a new-line as white-space, so it implicitly skips across that waiting new-line. Since there's (presumably) nothing else waiting to be read, it proceeds to wait for you to enter something, as you apparently desire.
If you want to use %c
for the conversion, you could precede it with a space in the format string, which will also skip across any white-space in the stream.
The ENTER key is lying in the stdin stream, after you enter a number for first scanf %d. This key gets captured by the scanf %c line.
use scanf("%1s",char_array); another=char_array[0];
.
use getch()
instead of scanf()
in this case. Because scanf() expects '\n' but you are accepting only one char at that scanf(). so '\n' given to next scanf() causing confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With