Question:
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;
do{
printf("Digite a primeira nota: ");
scanf("%i", &a1);
printf("\nDigite a segunda nota: ");
scanf("%i", &a2);
printf("\n\nMEDIA: %d", ((a1+a2)/2));
do{
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'));
}while(op!='n');
return 0;
}
Answer:
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
.