The problem is that the C language for repetitive statements do not break and repeat gk twice

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

I just want to print this out once, but even if I use do while, the same problem occurs. I know I made the wrong code, but I don't know what the problem is. I'd appreciate your help...

int main() {

    for (;;) {
        int i;
        char a;
        srand(time(NULL));

        printf ("number generator\n");
        printf("Generation number: ");

        for (i = 0; i <= 5; i++) {
            printf("%d ", rand() % 45 + 1);
        }

        printf("\nDo you want to recreate it? (y/n):");

        a = getchar();

        if (a == 'y') {}
        else if (a == 'n') {
            break;
        }
    }
}

c

2022-09-20 11:05

1 Answers

If you type y and press Enter, y will not only enter y in the input buffer, but will also be accompanied by a line break character called \n like y\n.

The getchar function is a function of getting Korean characters from the input buffer, so it was processed by taking y from the first loop, and \n from the second loop, so two runs occurred as an input.

a = getchar();

Fixing one line above as below is generally the recommended code. "%c" You must put a blank before %c like "%c". It's not a typo. The blank means the space in the input buffer (spacing, tab, enter, etc.). In other words, "%c" means to digest the space in the input buffer and then import the Korean character.

scanf(" %c", &a);

If you want to use getchar unconditionally, you can fix it as below.

while ((a = getchar()) == '\n');


2022-09-20 11:05

If you have any answers or tips


© 2022 pinfo. All rights reserved.