![]() |
VOOZH | about |
In C, scanf() is a standard input function used to read formatted data from the standard input stream (stdin), which is usually the keyboard.
Output
10 (Enter by user)
10
Explanation: `scanf("%d", &n)` reads an integer from the keyboard and stores it in variable `n`. Here, `%d` specifies an integer input, and `&n` gives the memory address where the value is stored.
The syntax of scanf() in C is similar to the syntax of printf().
Parameters:
Return Value:
We use & operator to find the address of the variables by appending it before the variable name and format specifier to recognize which type of data to be store.
Examples format specifiers recognized by scanf:
%d to accept input of integers.
%ld to accept input of long integers
%lld to accept input of long long integers
%f to accept input of real number.
%c to accept input of character types.
%s to accept input of a string.
If you're interested in learning more about input handling and integrating it into complex data structures, the C Programming Course Online with Data Structures covers practical applications of input functions in C.
The below examples demonstrate the use of scanf for different types of input:
Output
3.21 (Enter by user)
3.210000
`scanf("%f", &f)` reads a floating-point number from the user and stores it in variable `f`. Here, `%f` specifies a float input, and `&f` provides the memory address to store the value.
Output
3 7 (Enter by user)
3 7
Console
Geeks For Geeks (Enter by user)
Geeks
In the above example, we read a single input until the first space, so when "Geeks For Geeks" is entered, only "Geeks" will be stored in name. Also, we don't need to use the &operator for the address of name.
In C, scanf() provides a feature called scanset characters using %[] that lets you read a sequence of characters until a certain condition.
Output
Hello Geek (Enter by user)
Hello Geek
The code scanf("%[^\n]", name); reads a full line of text including spaces from the user and stores it in the array name. The printf("%s", name); then prints the entered text exactly as it was typed.