0

I am writing a program in CodeBlocks in C. I want to check if the input is in the right type and if not try to get it again.

My problem is whenever I'm trying to get the input with scanf and the input is incorrect it won't enter scanf again and just keep looping as if the input is always incorrect.

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

int main()
{
    float a = 0;

    while(scanf(" %f", & a) == 0)
    {
        printf("reenter");
    }

    printf("%f", a);

    return 0;
}

When I tried to enter incorrect value as 'y' the loop will go on:

enter image description here

If I will enter a current value it will get it as it should.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
uri2563
  • 33
  • 1
  • 8
  • 2
    scanf doesn't consume the input if it can't parse it. So it will parse y over and over again. – hko Dec 11 '19 at 22:25
  • 1
    Does this answer your question? [How to fix infinite loops when user enters wrong data type in scanf()?](https://stackoverflow.com/questions/58434411/how-to-fix-infinite-loops-when-user-enters-wrong-data-type-in-scanf) – hko Dec 11 '19 at 22:27
  • 2
    @hko — thanks for the duplicate search. I used the second (much older) question that you found as the reference. – Jonathan Leffler Dec 11 '19 at 22:47

3 Answers3

0

One way to approach this kind of thing is to take in a string (pick you poison on function) and then use sscanf to try and parse it.

foreverska
  • 585
  • 3
  • 20
0

In case of bad input entry, the input buffer is not consumed by scanf(), so you must read it additionaly in the way which guarantee successfull reading - for example as string.

See below:

int main()
{
    float a = 0;

    while (scanf(" %f", & a) == 0)
    {
        scanf("%*s"); // additional "blind" read

        printf("reenter");
    }

    printf("%f", a);

    return 0;
}
VillageTech
  • 1,968
  • 8
  • 18
0

You need to clean the input. Try with this

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

int main()
{
    float a = 0;

    while(scanf("%f", &a) == 0) {
        printf("reenter\n");
        while((getchar()) != '\n'); 
    }

    printf("%f", a);

    return 0;
}
Maverick
  • 56
  • 3