Input in C
In C, input can be from standard device from user like keyboard or from FILE. To use input function <stdio.h> header file must be included.
Syntax
scanf("format_specifier", &variable);
scanf takes two arguments
format_specifier | The type of data accepted as input. |
&variable | & returns the address of variable, followed by variable without space. |
Example
#include<stdio.h>
int main(){
int a;
printf("Enter a value: ");
scanf("%d", &a);
return 0;
}
Multiple input using scanf()
Single scanf() can accepts multiple inputs.
Example
#include<stdio.h>
int main(){
int a , b;
float f;
printf("Enter a value: ");
scanf("%d %d %f", &a, &b, &f);
return 0;
}
Explanation
"%d %d %f" | Format specifiers, must be separated with spaces. |
&a, &b, &f | Variable must be separated with comma, and must in the order of format specifiers. |
Integer Input using scanf()
For integer input %d format specifier is used.
#include<stdio.h>
int main()
{
int a;
printf("Enter a value: ");
scanf("%d", &a);
return 0;
}
float Input using scanf()
In C, for float input %f format specifier is used.
#include<stdio.h>
int main()
{
float flt;
printf("Enter a decimal value: ");
scanf("%f", &flt);
return 0;
}
Character input using scanf()
For character input %c format specifier is used.
#include<stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);
return 0;
}
String input using scanf()
For string input %s format specifier is used.
#include<stdio.h>
int main()
{
char *str;
printf("Enter a string: ");
scanf("%s", str);
return 0;
}