When we say for input in programming language it is about getting data from user (command line ) or from file. C programming provides various function for inputting the data. We will talk about mostly used library <stdio.h> and the functions scanf & printf.
Before we go for input and output we will learn about format specifier.
The below table shows the format specifier used by scanf and printf. The “Format specifier” is the sequence passed as the formatting string argument.
Format specifier | Characters matched | Argument type |
---|---|---|
%c | any single character | char |
%d, %i | integer | integer type |
%u | integer | unsigned |
%o | octal integer | unsigned |
%x, %X | hex integer | unsigned |
%e, %E, %f, %g, %G | floating point number | floating type |
%p | address format | void * |
%s | any sequence of non-whitespace characters,strings | char |
scanf function:
The int scanf(const char * format, …. ) function reads input from standard input stream stdin (keyboard) and stores the input according to format provided.
Example :
Q. Write a format specifier in scanf function to read two inputs from keyboard.
Ans :
1 2 |
int a,b; scanf("%d%d",&a,&b); |
&a , &b refers to the respective addresses.
printf Function:
The int scanf(const char * format, …. ) function writes output to the standard output stream stdout (screen) and prints output to the screen according to format provided.
Example:
Q. Write a printf format specifier to print two variables int and double values respectively.
1 2 3 |
int a=10; float b=11.10; printf("a=%d b="%f",a,b); |
Output:
a=10 b=11.10