0

I have a do-while loop that is supposed to only accept numbers between [0;26], integers, not unsigned. But when I type a letter or another character that is not a number, it accepts and initializes my integer as 0. Here is the code:

int cifra;
do
{
    printf("Insira a cifra a utilizar no intervalo [0;26]: ");
    scanf("%d", &cifra);
 }while(cifra > 26 || cifra < 0);
  • There have to be thousands of duplicates to this, but I'm to lazy to try and find a good one... So the problem is that if the `scanf` format specifier doesn't match the input, it doesn't remove the failing input from the buffer. So next iteration of the loop it will read the very same input as before. And again and again and again... I recommend you [read *lines*](https://en.cppreference.com/w/c/io/fgets) and then use `sscanf` to parse the line. – Some programmer dude Dec 09 '18 at 16:51
  • Possible duplicate of [How does scanf() reads when input is not in specified format?](https://stackoverflow.com/questions/27961609/how-does-scanf-reads-when-input-is-not-in-specified-format) – Matthieu Brucher Dec 09 '18 at 17:16

1 Answers1

0

If you want to use scanf you must do something like this: Please see the comments.

#include<stdio.h>
int main(void)
{
    int c,cifra,result;
    do
        {
            printf("Insira a cifra a utilizar no intervalo [0;26]: ");
            result=scanf("%d", &cifra); //on successful read result must be one.(one element)
            while ( ( c = getchar() ) != EOF && c != '\n' ) ; //empty the buffer
        }
    while(cifra > 26 || cifra < 0|| result!=1);

    printf("You did it\n");
}
manoliar
  • 172
  • 1
  • 8