3

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.

3
  • 2
    scanf doesn't consume the input if it can't parse it. So it will parse y over and over again. Commented Dec 11, 2019 at 22:25
  • 1
    Does this answer your question? How to fix infinite loops when user enters wrong data type in scanf()? Commented Dec 11, 2019 at 22:27
  • 2
    @hko — thanks for the duplicate search. I used the second (much older) question that you found as the reference. Commented Dec 11, 2019 at 22:47

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

3

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.