The steps for taking a number from the user using a faster input approach are as follows:
- The user is asked to enter a number.
- The number that will be entered by the user is accepted by the getchar_unlocked() function. Only one digit at a time is accepted by this function.
- The value entered by the user is first checked to ensure that it is a digit only. If it is not, the user is asked to re-enter the value.
- If the value entered by the user is a digit, its ASCII value is saved in the variable. This is because getchar_unlocked() assigns the ASCII value of the entered value to the variable.
- From the ASCII of the entered value, 48 is subtracted to convert it into the actual digit that the user has entered.
- If the digit is the first digit entered by the user, then it is simply assigned to another variable. But if it is not the first digit, then the existing digit in the variable is multiplied by 10 and the new digit is then added to the variable.
- Steps 2 through 7 are repeated for every digit entered by the user until the user presses the Enter key.
- The number in the variable is the actual number entered by the user and, hence, is displayed on the screen.
The program for entering a number using a fast input technique is as follows:
//fastinp.c
#include <stdio.h>
int getdata() {
char cdigit = getchar_unlocked();
int cnumb = 0;
while(cdigit<'0' || cdigit>'9') cdigit = getchar_unlocked();
while(cdigit >='0' && cdigit <='9') {
cnumb = 10 * cnumb + cdigit - 48;
cdigit = getchar_unlocked();
}
return cnumb;
}
int main()
{
int numb;
printf("Enter a number ");
numb=getdata();
printf("The number entered is %d\n",numb);
return 0;
}
Now, let's go behind the scenes to understand the code better.