Doubt C++ do-while loop


Well guys, I have the following question:

Every time I run this program the do-while loop does not stop on the scanf of the second loop in the program and ends up running twice and displaying the error message. I would like to know how to fix this bug.

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

int main(void){

int a1, a2, media;
char op;


    printf("Digite a primeira nota: ");
    scanf("%i", &a1);

    printf("\nDigite a segunda nota: ");
    scanf("%i", &a2);

    printf("\n\nMEDIA: %d", ((a1+a2)/2));

        printf("\n\nDigite 's' para rodar o programa denovo ou 'n' para encerrar: ");
        scanf("%c", &op);

        if ((op!='s') && (op!='n')){
            printf("Opcao invalida");

    }while((op!='s') && (op!='n'));     

return 0;


I advise you to use getchar() . To work with scanf you must clear the buffer with flush(stdin) because the enter \n is in stdin .

Scroll to Top