Home > Software design >  Clearing incorrect scanf inputs in C
Clearing incorrect scanf inputs in C

Time:11-17

I have scoured the internet and my textbooks and lectures for a way to fix this issue and nothing appears to be working.

I am using scanf to get an integer input, and need to validate the correct input.

However, when I put say, two characters or two numbers with a space inbetween into the scanf, it runs through twice instead of once as scanf hangs on to the unused data.

I cannot for the life of me find out how to either clear the scanf data, or to get it to read all of the input together as one incorrect input. I know how to clear the \n, just not the trailing characters that get left in the input.

int scan;
bool validInput = false;
int validScan;
int count = 0;
do 
{
    puts("Enter pin : ");
    validScan = scanf("%d", &scan);
    ((getchar()) != '\n');

    if(validScan !=1)
    {
        count  ;
        puts("Incorrect pin entered.");
    }
    else if(scan != PIN)
    {
        count  ;
        puts("Incorrect pin entered.");
    }
    else
    {
        validInput = true;
        count = 3;
    }
} while (count < 3);
return validInput;

CodePudding user response:

However, when I put say, two characters or two numbers with a space inbetween into the scanf, it runs through twice instead of once as scanf hangs on to the unused data.

You need to decouple the interpretation of the user input from reading the user input.

So instead of using scanf that does both at the same time:

int num1, num2;
bool success = (scanf("%d %d", &num1, &num2) == 2);

Use fgets to read it and sscanf to interpret it:

char buf[1024];
bool success = false;
if(fgets(buf, 1024, stdin) != NULL)
    success = (sscanf(buf, "%d %d", &num1, &num2) == 2);

See also scanf vs fgets and disadvantages of scanf.

CodePudding user response:

you could use fflush(stdin); before a scanf to clean the input.

  • Related