6

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?

Lundin
  • 195,001
  • 40
  • 254
  • 396
Jessica Lingmn
  • 1,162
  • 3
  • 10
  • 15
  • When You enter the `num` and press ENTER, so the ascii code of ENTER is stored in scanf buffer, and whenever you read next single character, it will not wait for user input and `ENTER` ascii code will be stored in `another` variable. – Adeel Ahmed Dec 11 '12 at 05:29

4 Answers4

10

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

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];.

anishsane
  • 20,270
  • 5
  • 40
  • 73
1

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.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
0
#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);
}
}
Adeel Ahmed
  • 1,591
  • 8
  • 10