Format String
Format string is the format for entered data. This format starts with % sign and followed by format specifier. Format specifier is a specific character which is used for which type of data is being read.
arg1, arg2, arg3… are the addresses of the variables where the entered data will be stored.
scanf() Function
Syntax: int scanf (“format string”, arg1, arg2, arg3…)
Some of the frequently used specifiers are as follows:
- d – Used for integer values.
- f – Used for floating number.
- c – Used for single character value.
- s – Used for strings.
Using single scanf() function, one or multiple input can be taken from the user.
The scanf() function takes input from the standard input (keyboard) and store the value in a variable. The function waits for the user input until the user press the enter key. Entered value is being stored in a buffer. When enter key is being pressed, scanf() function starts to read.
Example1: Integer Input
In Example1.c, we have seen that when we entered integer values and press the enter key. The scanf() function takes the value and stored it in the variable. If we enter the values separated by space, the function returns when space is encountered but the values after space remains in the input buffer. That’s why the second scanf() function will not wait for user input, instead it takes the input from the buffer.
Example 2: Single Character Input
In Example2.c, we have seen that when we use %c specifier, the scanf() function takes only one character even if we have entered more than one character.
Example 3: Single Character Input (Multiple Times)
Example 4:
Example 5: String Input
getc() Function
Syntax: int getc(FILE *stream)
getc() function is used to read a character from the FILE pointer (stream). To read from keyboard, we have to use stdin. This function returns an integer value of read character.
Example 6:
getchar() Function
Syntax: int getchar(void)
getchar() function is same as getc(). The only difference is that getc() function can read from any input stream, whereas getchar() function reads from standard input only.
Example 7:
Conclusion
In this article, we have seen how input functions are used in C language. All these functions are taken input from the input buffer and when we use these functions multiple times, we have to clear the buffer. Otherwise, the functions will not wait for user input and take the input from the buffer.