0

Currently im trying to learn simple C Programs. But, i came into this situation :

#include<conio.h>
#include<stdio.h>

void main()
{
   char c;
   int tryagain=1;

   while(tryagain>0){
       printf("Enter the Character : ");
   scanf("%c",&c);
       printf("You entered the character \"%c\" and the ascii value is %d",c,c);

    getch();
    clrscr();
    tryagain=0;

    printf("You want to Trry again Press 1 : ");
    scanf("%d",&tryagain);
    clrscr();

    }
 }

The program is fine when user first enter a character. And, when it ask to continue. And, user enter 1 then it is behaving weired. It automatically input blank character and prints the ascii and goto the same place.

How can i resolve this? And, specially, Why is the reason for this?

And, Im sorry about my poor english!

Thank you in Advance.

Santosh A
  • 5,173
  • 27
  • 37
N Subedi
  • 2,858
  • 2
  • 22
  • 36

2 Answers2

4

When you use

scanf("%d",&tryagain);

the number is read into tryagain but the newline character, '\n', is still left on the input stream. The next time you use:

scanf("%c",&c);

the newline character is read into the c.

By using

scanf("%d%*c",&tryagain);

the newline is read from the input stream but it is not stored anywhere. It is simply discarded.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

The issue is that you are reading a single number in the second scanf, but user inputs more than a single number there, the user also input a new line character by pressing .

User enters "1\n". Your scanf reads "1", leaving out "\n" in the input stream. Then the next scanf that reads a character reads "\n" from the stream.

Here is the corrected code. I use getc to discard the extra new line character that is there.

#include <stdio.h>

void main()
{
    char c;
    int tryagain = 1;

    while (tryagain > 0) {
        printf("Enter a character: ");
        scanf("%c", &c);
        printf("You entered the character \"%c\" and the ascii value is %d\n", c, c);

        tryagain = 0;

        printf("If you want to try again, enter 1: ");
        scanf("%d", &tryagain);
        // get rid of the extra new line character
        getc(stdin);
    }
}

Also, as a side note, you use conio.h which is not part of standard C, it's MS-DOS header file, thus it's not portable C you are writing. I have removed it from my code, but you might wish to keep it.

John Berger
  • 175
  • 9
  • Using `fflush(stdin)` [is discouraged](http://stackoverflow.com/questions/2979209/using-fflushstdin). – user3386109 Dec 12 '14 at 03:21
  • Okey. Thank you so much John. You given me the detailed info so, im going to accept your answer. Thank you again. – N Subedi Dec 12 '14 at 03:22