Putting what you have already got into the other code responses, you can test the return of scanf
until you give 1
signaling that you were able to read 1
integer successfully:
int x;
while (scanf("%d", &x) != 1){ //enquanto não ler 1 inteiro
static char temp[256];
fgets(temp, sizeof(temp), stdin); //limpa tudo o que ficou na entrada lendo como string
printf("Digite um numero ");
}
Although it may seem a little annoying to have to write this all down to make sure it reads an integer, it's something you can easily abstract in an auxiliary function:
int ler_inteiro(){
int num;
while (scanf("%d", &num) != 1){
static char temp[256];
fgets(temp, sizeof(temp), stdin);
printf("Digite um numero ");
}
return num;
}
int main() {
int x = ler_inteiro();
int y = ler_inteiro();
printf("%d %d", x, y);
}
See this example in Ideone
Another somewhat harder possibility would be to always read everything as string and interpret the data you want from the string read. In case an integer could try to interpret an integer at the expense of strtol
and check if it was unsuccessful ask for another one again.