I need to use scanf to input an 8 digit number with no extra "junk" characters after the number (e.g. 12345678k), just the number, or else a prompt to re-enter. i know scanf isn't recommended but this is the second week of class and it's the only function of its kind we've learned so far ( besides getchar() for flushing the input buffer).
this is what i have so far:
Code:
/*
This program prompts the user to setup a pin
It handles invalid input properly
*/
#include <stdio.h>
/* Complete the code for this program below */
int main()
{
int acctNum, pinNum, temp, numDigits = 0;
char ch;
printf("Please enter your 8 digit account number: ");
scanf("%d%c", &acctNum, &ch);
/* Calculates numbers of digits in number entered */
temp = acctNum;
while(temp)
{
temp = acctNum/10;
numDigits++;
}
while(numDigits != 8 || ch != '\n')
{
/* Flushes input buffer */
while(getchar() != '\n');
printf("Invalid account number. Account number must be 8 digits.\n\n");
printf("Please enter your 8 digit account number: ");
scanf("%d%c", &acctNum, &ch);
/* Calculates numbers of digits in number entered */
while(temp)
{
temp = acctNum/10;
numDigits++;
}
}
return 0;
}
problem is, i think i'm having trouble with the \n and scanf. here's what happens:
If i input valid number first time = program ends succesfully
If i input an invalid number first try (e.g. 123456789), i must press <enter> twice and then it prompts me to re-eneter, but every input after that is returned as invalid even if it is valid ( i also must press <enter> twice for all these inputs).
where am i going wrong?
thanks