Managing Input and Output Operations
Reading character: Reading a single character can be done by using the function getchar(). The getchar takes the following form:
variable_name=getchar();
variable_name is a valid C name that has been declared as char type().
For example: char name;
name=getchar();
#include<stdio.h>
void main( ) {
char answer;
printf(“Would you lik to know my name?\n”);
printf(“Type Y for YES and N for NO:=\n”);
answer=getchar();
if (answer==’Y’ || answer==’y’) printf(“My name is Tuhin:=\n”);
else
printf(“You are good for noting:=\n”);
}
Writing a character : putchar () function for writing character one at a time to the terminal. It takes the form as shown below:
putchar (variable_name);
For example:
char answer;
answer=’Y’;
putchar(answer);
#include<stdio.h>
#include<ctype.h>
void main( ) {
char alphabet;
printf(“Enter an alphabet:=\n”);
alphabet =getchar();
if (islower(alphabet)) putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
}
Some functions:
isupper(c) islower(c) isalnum(c) isalpha(c) isdigit(c) isspace(c) tolower()\
toupper()
formatted input:
scanf(“%d %d %d”, &a, &b, &c);
An input field may be skipped by specifying * in the place of field width. For example , the statement
scanf(“%d %*d %d”, &a, &b, &c);
will assign the data 123 456 789 as follows:
123 to a 456 skipped 786 to b
c shows 0 ( visual studio 6 compiler)
Formatted output:
printf(“%d”,9876);
printf(“%6d”,9876);
printf(“%2d”,9876);
printf(“%-6d”,9876);
9 8 7 6
9 8 7 6
9 8 7 6
9 8 7 6
0 0 9 8 7 6
printf(“%06d”,9876);
printf(“%7.4f”,98.7654);
printf(“%7.2f”,98.7654);
char name[15]="I am tuhin";
printf("%.3s", name );
result: I a char name[15]="I am tuhin";
printf("%.6s", name );
result: I am t char name[15]="I am tuhin";
printf("%010.6s", name );
EXAMPLE : Here is an outline of a typical C program that makes use of several input/output routines from the standard C library.
/* sample setup illustrating the use of input/output library functions * /
#include <stdio.h>
void main ( ) {
char c,d; / * declarations * / f loat x,y;
int i, j, k ;
c = getchar( ); /* character input */
scanf ( " % f " , &x) ; /* f l o a t i n g - p o i n t input */
scanf ( "%d %d", &i, &j) ; / * integer input * /
d= ‘A’; / * assignment statements */
putchar(d); / * character output */
printf("%3d %7.4f", k, y ) ; / * numerical output */
}
9 8 . 7 6 5 4
9 8 . 7 7
0 0 0 0 I result: a m t