In C Language, "scanf()" is a standard library function used to read formatted input from the standard input stream (usually the keyboard).
It is declared in the header file
The "scanf()" function allows us to accept input from the user during program execution and store it in variables.
int scanf(const char *format, ...);
format: A string that specifies the format of the input expected. It may contain format specifiers, which indicate the type of data to be read and how it should be interpreted.
"...": A variable number of pointers that correspond to the variables where the input values will be stored.
Format specifiers begin with the percent sign "%" and are followed by a character that specifies the type of data to be read.
Some commonly used format specifiers are:
"%d" or "%I": we can accept the integer values of variables using format specifiers.
"%f": we can accept the Floating Point values of variables using format specifiers.
"%c": we can accept the Character values of variables using format specifiers.
"%s": we can accept the String values of variables using format specifiers.
#include <stdio.h> int main() { int num; float f_num; char ch; char str[50]; printf("Enter an integer value: "); scanf("%d", &num); printf("Enter a float value: "); scanf("%f", &f_num); printf("Enter a character value: "); scanf(" %c", &ch); // Note: Leading space to consume any whitespace characters printf("Enter a string value: "); scanf("%s", str); printf("Integer Value: %d\n", num); printf("Float Value: %.2f\n", f_num); // Displaying float with 2 decimal places printf("Character Value: %c\n", ch); printf("String Value: %s\n", str); return 0; }
// Entering Mock Data for demo purpose. Enter an integer value: 20 Enter a float value: 3.14 Enter a character value: H Enter a string value: Hello World, in C Language Integer Value: 20 Float Value: 3.14 Character Value: H String Value: Hello World, in C Language
It allows us to accept formatted input from the user, making it a fundamental function for interactive C programs.
It's important to be cautious while using "scanf()" to avoid potential issues like buffer overflow or incorrect input handling.