Basic I/O Operations in C
BASIC I/O OPERATIONS in C
In this tutorial we will learn to read data from standard input device and write data on standard output devices
The header file required by every program containing standard input/output functions is “stdio.h”
Syntax:- #include <stdio.h>
- Stdio stands for “standard input/output”.
- The contents of header files becomes a part of compiled code.
READING A CHARACTER
For reading a single character from input device, getchar() is used.
Syntax:- variable_name= getchar();
Statements stores the character entered from input device into the variable “variable_name”.
WRITING A CHARACTER
Putchar() function is used to write a single character on console.
Scanf() function is used to take multiple inputs of different or same data types at a time.
Syntax:- scanf(“control string", arg1, arg2,.....argn);
Control string describes the data type to be entered and the field width of data type.
arg n defines the address of the memory location in which that data type variable is stored.
Scanf(“%5d %c %s”, &num, &choice, name);
Here in this example scanf() takes input to 3 variables of three different data type i.e. integer, character and string variables respectively. During the run time scanf() will accept an integer value from the standard input device and after that a character and then a string.
If the variables are given values in any other order then unexpected results will be obtained depending on different situation.
- NOTE:- it is legal to use a non-whitespace character between field specifications. However, the scanf expects a matching character in the given location.
Accepts input like
to assign Y to choice and 123 to num.
- In case of taking string as a input, it is also possible to restrict the input string to contain only a specified set of character by writing control string as %[characters]
Here scanf() will accept only alphabets from a to z. Anything other than that will be ignored.
printf() function is used to print any string or any textual line you want to add to the output.
It also prints multiple values of multiple data types along with a any textual string the coder wants to add, all at a same time, and it also makes our output much more readable and formatted.
SYNTAX:- printf(“control string”, arg1, arg2,.....arg n);
Here, control string is almost same as in scanf() function. But here we can add any textual matter of our choice to the screen.
Unlike of scanf(), here arg n contains the variable instead of address of variable.
If a=5, b=6
We give following statement in our code:-
Printf(“Output of the program is a = %d and b=%b”, a,b);
Then the output will be like:-
Output of the program is a = 5 and b=6