Yes, there are already similar issues on SO on that scanf()
does not wait for the user's input before "interpreting" an enter keypress, but my problem is that this problem only occurs when the scan -- which is %ld
(with a space in front) -- reads a string instead of another long number. Details are below if this summary seems convoluted.
I have the following program in C:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
long int cardnum, tmp;
int num_of_digits;
bool validate; // valid value
LOOP:do
{
printf("Number: ");
scanf(" %ld", &cardnum);
tmp = cardnum, num_of_digits = 0;
while (tmp != 0)
{
tmp /= 10;
++num_of_digits;
}
if (num_of_digits != 16)
{
printf("INVALID\n");
goto LOOP;
}
validate = false;
// ... (validate will be processed here, and there will be a case where "validate" will be true)
}
while (validate != true);
}
Inputs:
4003600000000014
: works, length is 16400360000000001
: printsINVALID
, length is 15asdf
: infinite loop (notice how not all invalid inputs will result in this bug!)
Number: INVALID
Number: INVALID
Number: INVALID
...
I have read elsewhere that scanf
ignores the last line buffer (or something) but in my case, it only happens when scanf
did not receive the right input type from the user. Can anyone please help?
Thanks in advance.