Search code examples
cbufferstdinflush

%d placeholder input '3abc', cannot clear 'abc' buffer


Below is my code:

int length;
char ch;

printf("\n\tEnter the length of the password: ");
while (scanf("%d", &length) != 1) {

    printf("\n\tPlease enter digit only.\n");
    printf("\n\tEnter the length of the password: ");

    while ((ch = getchar()) != '\n' && ch != EOF);
}

printf("\n\tEnter the number of passwords you want: ");
while (scanf("%d", &num) != 1) {

    printf("\n\tPlease enter digit only.\n");
    printf("\n\tEnter the number of passwords you want: ");

    while ((ch = getchar()) != '\n' && ch != EOF);
}

When I entered abc okay.

When I entered 3abc, 3 is received by length, but the 'abc' still in the buffer.

I used while ((ch = getchar()) != '\n' && ch != EOF); to clear but still not working?

Any help from the expert is appreciated.


Solution

  • You are not flushing the stdin if a number was correctly grabbed by scanf as your test case 3asc

     int length;
     int ch;
    
     printf("\n\tEnter the length of the password: ");
     while (scanf("%d", &length) != 1) {
    
         printf("\n\tPlease enter digit only.\n");
         printf("\n\tEnter the length of the password: ");
    
         while ((ch = getchar()) != '\n' && ch != EOF);
     }
    
     // flush stdin
     while ((ch = getchar()) != '\n' && ch != EOF);
    
     printf("\n\tEnter the number of passwords you want: ");
     while (scanf("%d", &length) != 1) {
    
         printf("\n\tPlease enter digit only.\n");
         printf("\n\tEnter the number of passwords you want: ");
    
         while ((ch = getchar()) != '\n' && ch != EOF);
     }
    

    And, already commented, to recognize ch != EOF ch must be int. Moreover getchar prototype is int getchar(void)