简体   繁体   中英

scanf not working well in C

    if (a % 5)
            goto ask;
            else
            goto main;

ask:printf("Do You Want To Exit ? Y \\ N . . . \n");
        scanf("%c", &YN);
        getch();
        if (YN == 'Y')
        {
y:          system("cls");
            YN = 1;
            goto sign;
        }
        else if (YN == 'y')
            goto y;
        else if (YN == 'N')
        {
n:          system("cls");
            YN = 0;
            goto sign;
        }
        else if (YN == 'n')
        {
            goto n;
        }
        else
        {
            printf("Sorry ..Didn't Catch that ... ");
                goto ask;
        }

someone help me understand my problem for somereason the output I get from this code is "Do u want to exit y\\n ?" getchar ... "sorry didnt catch that do u want to exit y\\n ? "

It looks like it jumped over the scanf() for the first time and the program went directly to the else ==> "sorry i didnt get that" and only in the second time it fiugres out how to use the scanf() .

scanf() reads characters with %c and yes, the ENTER key press [after your previous input] is pretty much vaild for %c [Check the below spoiler].

ENTER key press == newline

use

scanf(" %c", &YN);  //mind the space brefore `%c`
       ^
       |

to ignore any previously-stored [also, leading] whitespace [including a newline.]

Note: This also eliminates the need for your getch();

When scanf reads anything, it leaves the newline added by the Enter in the input buffer. The "%c" format reads any character in the input buffer, including newlines. So the first call will read and extract one character from the input buffer, but the next call will read the newline character left over from the previous call.

Adding a leading space to the format string tells scanf to read (and ignore) any whitespace (space, tab, newlines) before it tries to parse and extract your format.

I recommend you read eg this scanf reference for more information.

Add a space before %c to skip the newline character from the stdin which you had pressed after entering data for the scanf for the first time. This happens because scanf does not consume the \\n character(Enter key) which you press after you enter any character .As the Enter key( \\n ) is also a character,it gets consumed by the scanf the second time and hence does not wait for further input.

Also,using goto s is usually bad practice. See this for more info about this.

删除getch()您基本上要做两次相同的事情。

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