Lesson 5: Managing Input and Output Functions.
Prev || Home || Next
We have oftenly used two functions printf and scanf for writing of data and reading of data from terminal. Each program that uses a standard input/output function must contain the statement
However, this is not necessary for printf and scanf, stdio.h stands for standard input-output header file.
Reading a Character:
Reading a single character from terminal can be done by using the function getchar().
ex. char name;
When this statement is encountered, the computer waits until a key is pressed and then assigns this character as a value to getchar function. In the above example if key H on the keyboard is pressed while execution of progra,, it will be stored in the variable name.
printf("Would U like to know mu name?\n");
printf("Type Y for yes and N for no");
if(answer=='y' || answer=='Y')
printf("\nMy name is Computer");
printf("U are good for nothing");
Program:- For testing whether entered character is numeric/alphanumeric or alphabetic using character type function.
printf("Press any key\n");
printf("The character is a letter");
printf("The character is a digit");
printf("The character is alphanumeric");
Like getchar(), there is a function putchar() for writing characters one at a time.
this will display Y on the screen.
Program:- getchar() example.
printf("\nEnter an alphabet");
Formatted input refers to an input data that has been arranged in a particular format.
Consider the following data:
15.57 123 Radha
These are three types of data. First should read into a variable float, the second into int and the third into char. This is possible in C using scanf function.
Control string: It must contain a format specification consisiting a conversion character % and a type specifier and an optional number specifing fieldwidth.
%wd -- Field Specification for reading an integer number.
Consider following examples:
Here you can assign maximum 2 digit integer number to variable num1 and 5 digit to variable num2.
Here you can read a number with maximum two decimal places and assign it to variable amt.
printf function can be effectively used to print formatted output on the screen.
Control string consists of three types of items
1) Characters that will be printed on screen as they appear
ex. printf("Hello! How R U?");
2) Format specifications that define the output format for display of each item.
3) Escape sequence characters.
Output of real numbers:-
Printing of Strings:
The effect of a variety of specifications in printing a string "NEW DELHI - 111001" containing 16 characters is as below
|%s||NEW DELHI _ 111001|
Prev || Home || Next