The program that you enter in the do while statement, it works once, but then it's weird.

Asked 2 years ago, Updated 2 years ago, 141 views

#include <stdio.h>

int main(void)
{
    char ch;
    int x, y;
    int result;

    printf("*****************\n");
    printf("A--- Add\n");
    printf("S--- Subtract\n");
    printf("M--- Multiply\n");
    printf("D--- Divide\n");
    printf("Q--- Quit\n");
    printf("*****************\n");

    do
    {
        repeat :
        printf("Select operation:");
        ch = getchar();
        printf("Enter two numbers separated by a space: ");
        scanf_s("%d %d", &x, &y);

        if (ch == 'A')
            result = x + y;
        else if (ch == 'S')
            result = x - y;
        else if (ch == 'M')
            result = x * y;
        else if (ch == 'D')
            result = x / y;
        else if (ch == 'Q')
            break;
        else
            goto repeat;

        printf("%d\n", result);

    } } while (1);

    return 0;
}

For the first run, "Select an operation" and "Enter two numbers separated by a space" are normally output, but it's weird from the second run, why is it output at once?

c scanf

2022-09-20 15:49

1 Answers

int main(void)
{
    char ch;
    int x, y;
    int result;

    printf("*****************\n");
    printf("A--- Add\n");
    printf("S--- Subtract\n");
    printf("M--- Multiply\n");
    printf("D--- Divide\n");
    printf("Q--- Quit\n");
    printf("*****************\n");

    do
    {
    repeat:
        printf("Select operation:");
        //ch = getchar();
        while (1) {
            ch = getchar();

            if (ch != '\n')
                break;
        }

        printf("Enter two numbers separated by a space: ");
        scanf_s("%d %d", &x, &y);

        if (ch == 'A')
            result = x + y;
        else if (ch == 'S')
            result = x - y;
        else if (ch == 'M')
            result = x * y;
        else if (ch == 'D')
            result = x / y;
        else if (ch == 'Q')
            break;
        else
            goto repeat;

        printf("%d\n", result);


    } } while (1);

    return 0;
}

After doing the first getchar() and scanf_s(), '\n' remains in the input buffer without flushing, and when the second getchar() is executed, it is a problem that occurs before user input, so \n is corrected to discard. I hope it was helpful.


2022-09-20 15:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.