The user is asked to enter a number. A user-defined getdata() function is invoked and the value returned by the function is assigned to the numb variable, which in return is then displayed on the screen. The getdata function will keep asking for the digits of the number and will return the number when the Enter key is pressed.
Let's assume that the user wants to enter 20. Within the getdata function, the getchar_unlocked() function is invoked. So, on entering the first digit, 2 (of the number 20), it will be assigned to the cdigit variable, which is of the character data type. The ASCII value of 2 is 50, so the value 50 is actually assigned to the cdigit variable.
Before proceeding further, we ensure that the value entered by the user is a digit, and not a character or some other symbol. If the user enters something other than a digit, the getchar_unlocked() function is again invoked, asking the user to enter a valid digit. If the value entered is a digit, then 48 is subtracted from its ASCII value to convert it to its actual value. This is because the ASCII value of 2 is 50; on subtracting 48 from 50, the result will be 2, which is the actual digit that was entered by the user. The value of 2 is assigned to the cnumb variable.
Since the next digit of the number 20 is 0, the getchar_unlocked () function is invoked and the value 0 is assigned to the cdigit variable. Again, it is checked that the value entered by the user is a digit and nothing else. The ASCII value of 0 is 48. From the ASCII value of 0, the value 48 is subtracted to make its value 0. The current value in cnumb is 2, which is then multiplied by 10 and the value of cdigit is added to the result. The result of this computation will be 20 and it is assigned to the cnumb variable. The value in the cnumb variable is returned to the main function to be displayed.
In short, whatever digit is entered by the user, its ASCII value is assigned to the variable and the numerical value 48 is subtracted from the ASCII value of the digit to convert it into the actual digit that was entered by the user.
The program is compiled using GCC, as shown in the following screenshot. Because no error appears on compilation, that means the fastinp.c program has successfully been compiled into an EXE file, fastinp.exe. On executing the file, the user is prompted to enter a number. The number is accepted using a fast input technique. After entering all the digits of the number, when the user presses the Enter key, the entered number is displayed on the screen as shown in the following screenshot:
Voilà! We have successfully configured faster input of numbers in C. Now let's move on to the next recipe!