By putting what you already got in the other code answers, you can test the return of scanf
until 1
which signals that it has been able to read 1
entire 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 bit boring to have to write all this to make sure you read 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 possibility a little more laborious would be to always read everything as a string and interpret the data you want the string to read. In case a whole could try to interpret a whole at the expense of strtol
and check if you were unsuccessful to re-order another.
Good answer, I thought to write something like this but I got lazy. : ) In fgets to clean the input buffer it might be better to use BUFSIZ instead of 256. I don’t know why these courses insist on using scanf, only gives problems, and in my experience this is never used in programs "really".
– zentrunix
@zentrunix Thanks for the comment. Yes it is best to use
sizeof
which is one less place to trade, which is what I usually do this time it didn’t even occur to me.– Isac