Question

When I enter 0 the program ends. But there is getchar() in if statement and it doesn't work, can you help me?

On case 0 I want it to get char from user. If 'N' or 'n' is entered the program will end but if not the program will start over again. (from sec1).

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;

    sec1:
    printf("Select a number between 4 and 0: ");
    scanf("%d[\n]", &n);

    switch(n)
    {
        case 0:
            puts("Are you sure?");
            puts("Yes(Y) or No(N)");
            if(getchar() == 'N') goto sec1;
            break;

        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        case 4:
            break;

        default:
            puts("Only numbers between 4 and 1 are accepted!");
            goto sec1;
            break;

    }
    system("pause");
    return 0;
}

working one

int main()
{
    int n, c;

    sec1:
    printf("Select a number between 4 and 0: ");
    scanf("%d/n", &n);

    switch(n)
    {
        case 0:
            puts("Are you sure?");
            puts("Yes(Y) or No(N)");
            fflush(stdin);
            if (getchar() == 'N') goto sec1;
            break;

        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        case 4:
            break;

        default:
            puts("Only numbers between 4 and 1 are accepted!");
            goto sec1;
            break;

    }
    system("pause");
    return 0;
}
Était-ce utile?

La solution

Change

scanf("%d[\n]",&n);

to

scanf("%d\n",&n);

The reason that your original code does not work is because scanf wants to read an integer, a "[", a "\n" and a "]". So when you input an integer followed by a "\n", scanf only takes the integer(because it expects to see a "["). Then the getchar will simply take the remaining "\n". That's why your getchar() seems not working.

Hope it is helpful to you!

Autres conseils

Probably you have some symbols in the input buffer when you are reading "N" or "n". You need to flush an input buffer before new reading. See this question for details.

Briefly just write: while (getchar() != '\n') {} right after scanf(...).

I guess this is the terminal which is in cooked mode, thereby only feeding typed characters to the program when the user completes a line by hitting return. You can test it by feeding it input from a pipe instead of interactively from the terminal.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top