-1

I had difficulties while executing the following code. The variable 't' take a null value after complete one execution. The problem was solved by using getch() instead of scanf(). But i don't know why it's happening. Any explainations ? This is the program which didn't work.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
char t;
void main()
{
    while(1)
    {
        scanf("%c",&t);
        printf("\nValue of t = %c",t);
        printf("\nContinue (Y/N):");
        char a=getche();
        if(a=='n' || a=='N')
        exit(0);
   }
}

Now, this is the program which executes correctly.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
char t;
void main()
{
    while(1)
    {
         t=getch();
         printf("\nValue of t = %c",t);
         printf("\nContinue (Y/N):");
         char a=getche();
         if(a=='n' || a=='N')
         exit(0);
    }
}
devKeshav
  • 41
  • 1
  • 5
  • possible duplicate of [Odd loop does not work using %c](http://stackoverflow.com/questions/13814128/odd-loop-does-not-work-using-c) – Michael Foukarakis Feb 18 '13 at 19:03
  • `void main()` is not a legal *signature* for hosted implementations (... unless they have extensions) – pmg Feb 18 '13 at 19:30

1 Answers1

9

When you read a character,

scanf("%c",&t);

there's a newline left behind in the input stream which causes the subsequent scanf() to skip input in the loop.

Note that getch() is non-standard function. You can use getchar() instead.

Or Change it to:

scanf(" %c",&t); 

Notice the space in the format specifier which ensures all the whitespaces are skipped by scanf() before reading a character for %c.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • I've read this same answer to this same question over and over again on SO. Why is it that each time I read them my palm still smacks into my forehead. I'll remember it this time though! – Nocturno Feb 18 '13 at 19:45
  • Thanks @KingsIndian , It would be very kind of you if you can explain me the same program when executed using %s instead of %c. – devKeshav Feb 19 '13 at 14:04
  • @KeshavAgarwal Even when you read a string (using `%s`), the newline character is still there in input stream. You might have a problem only if you try to read something *after* that. For example, if you do: `scanf("%c", &ch);` right after reading a string, then you'll see the same problem that it won't read a character for `ch` due to newline. But if you read an int: `scanf("%d", &i);` then you won't see this problem because scanf expects an integer for %d, so it'll skip the newline character. – P.P Feb 19 '13 at 14:50