scanf not working well in C

c scanf

165 просмотра

4 ответа

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

ask:printf("Do You Want To Exit ? Y \\ N . . . \n");
        scanf("%c", &YN);
        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;
            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().

Автор: unix14 Источник Размещён: 12.11.2019 09:14

Ответы (4)

1 плюс


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


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();

Автор: Sourav Ghosh Размещён: 19.11.2014 11:36

1 плюс

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 e.g. this scanf reference for more information.

Автор: Some programmer dude Размещён: 19.11.2014 11:39

0 плюса

Remove getch() you are basically doing the same thing twice.

Автор: Zak Размещён: 19.11.2014 11:40

0 плюса

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 gotos is usually bad practice. See this for more info about this.

Автор: Spikatrix Размещён: 19.11.2014 11:37
Вопросы из категории :