简体   繁体   中英

C Program :Error when reading character from stdin using scanf

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM