Question

I was solving a programming problem in C language, came across in a book

the code was as following :-

#include<stdio.h>
#include<conio.h>
void main()
{
     int num;
     char another;
     do
     {
          printf("Enter a Number");
          scanf("%d",&num);
          printf("Square Of The Entered Number Is = %d",num*num);
          printf("Do You Still Want To continue (y/n)");
          scanf("%c",&another);

     }while(another=='y');

     getch();
}

Now when i ran this programme in "TurboC++ MSDOSBox for Windows 7"

programme exits even if I enter "y" after following statement "Do You Still Want To Continue(y/n)"

Looks Like it is not executing any statement after this one

scanf("%c",&another);

because i have added another statement after this one as :-

scanf("%c",&another);
printf("another is = %c",another);

but the value of another never got printed. the programme exits directly

Was it helpful?

Solution

The problem here is that when you scan for the number, it leaves the newline that you end the input with in the input buffer. So when you later scan for the character, it will read that newline.

The fix is very simple: Tell scanf to skip leading whitespace (which includes newline) before reading your character. This is done by adding a space in front of the format code:

scanf(" %c",&another);
/*     ^      */
/*     |      */
/* Note space */

When you enter the number for the first scanf call, there is an input buffer that will look like

+--+--+--+--+
| 1| 2| 3|\n|
+--+--+--+--+

if you input the number 123. After the scanf function reads the number, the buffer will look like

+--+
|\n|
+--+

In other words it contains only the newline character. Now when you do the second scanf to read a character, the scanf function sees this newline, and as it's a character, it is happy and returns that newline to you in the another variable.

What adding a space in the scanf format string does, is to tell scanf to skip over any whitespace, which includes newline, carriage return, space and tab. It will then find the character you actually wanted to input and read that.

Also, most format specifiers automatically skips leading whitespace, like the "%d" specifier. But when scanning for characters it's not possible, as the caller may actually want the newline character.

OTHER TIPS

Another simple way is to use the functions specially meant for reading characters

Replace scanf("%c",&another); by another=getch(); or another=getchar()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top