Scanf() introduction
In this article, let’s explore another important ‘C’ library function scanf().
scanf()
- scanf() is a standard library function that allows you to read input data from standard in.
- Standard in for us is generally the keyboard. If you are working on your computer, then usually a standard in means the keyboard. If it is an embedded system, then it may not be the keyboard. So, it may be a touchscreen, or it may be a keypad like that.
- By using scanf library function you can read both characters and numbers from the keyboard.
Let’s explore how to use scanf. Look at the code snippet here, as shown in Figure 1. Here is a variable definition age, and in this code, you are asking the user to enter the age. scanf is how the user data is read inside the program.
Observe &age. Here, whatever the user enters is usually the number. So, that is put into the address of the variable. What scanf does is, whatever the value you enter, it will be read from the input stream, and it will be saved at the address of the age variable. That’s the reason you have to mention the address operator here, so the address of age (&age). “%d” is a format specifier.
ā%dā ā scanf reads an integer(a number) which the user enters
&age ā scanf puts that read value “At the address of ” ‘age’ variable.
For example, now, I enter the number, let’s say 8. When I enter 8 from my keyboard, the number 8 is stored at the address of age, not its ASCII equivalent. So, you have to remember that. Because I have used the format specifier %d. So, I want a number to be stored in the variable.
Suppose I use format specifier %c here, then its ASCII equivalent will be stored in variable age. That is 56. That’s how you should differentiate.
What actually should be stored in the variable?
You can decide that by using the format specifier.
I want to store a character. That means an ASCII value of the character into the variable. In this case, I use format specifier %c, as shown in Figure 2. Suppose if I enter the letter A, then its ASCII value will be stored in the variable c.
There is one more library function called getchar(). This is also used to read input from the standard in.
getchar()
- If you just want to read a single character from the keyboard in ASCII format then just use getchar().
- getchar() function takes no argument and just returns an int value which happens to be the ASCII value of the key pressed.
- For example, int a = getchar(); //Here the program hangs until you press a key from your keyboard followed by pressing the enter key.
In the following article, we’ll do one exercise using scanf and other functions. The exercise is, Write a program which takes 3 numbers from the user. And the program should compute the average of those numbers, and the result must be printed.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1