scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It reads data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments.
- It accepts character, string, and numeric data from the user using standard input.
- Scanf also uses format specifiers like printf.
Syntax:
int scanf( const char *format, … );
Here,
- int is the return type.
- format is a string that contains the type specifiers(s).
- “…” indicates that the function accepts a variable number of arguments.
Example type specifiers recognized by scanf:
%d to accept input of integers.
%f to accept input of real number.
%c to accept input of character types.
%s to accept input of a string.
Example:
int var;
scanf(“%d”, &var);The scanf will write the value input by the user into the integer variable var.
Return Values:
>0: The number of values converted and assigned successfully.
0: No value was assigned.
<0: Read error encountered or end-of-file(EOF) reached before any assignment was made.
Why &?
While scanning the input, scanf needs to store that input data somewhere. To store this input data, scanf needs to known the memory location of a variable. And here comes the ampersand to rescue.
- & is also called as address of the operator.
- For example, &var is the address of var.
Below is the C program to implement scanf:
C
// C program to implement // scanf #include <stdio.h> // Driver code int main() { int a, b; printf ( "Enter first number: " ); scanf ( "%d" , &a); printf ( "Enter second number: " ); scanf ( "%d" , &b); printf ( "A : %d \t B : %d" , a , b); return 0; } |
Output:
Enter first number: 5 Enter second number: 6 A : 5 B : 6