[go: up one dir, main page]

0% found this document useful (0 votes)
31 views34 pages

Chap 4

The document discusses input and output operations in C programming. It covers reading single characters and strings from keyboard, writing characters to screen, and formatted input of integers, floating point numbers, and mixed data types using scanf function. It also discusses detecting errors in input.

Uploaded by

Rahul Prasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views34 pages

Chap 4

The document discusses input and output operations in C programming. It covers reading single characters and strings from keyboard, writing characters to screen, and formatted input of integers, floating point numbers, and mixed data types using scanf function. It also discusses detecting errors in input.

Uploaded by

Rahul Prasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Managing Input Output

Operations
Introduction to Input and Output
• Reading, processing, and writing of data are the three essential functional functions
of a computer program.
• Most programs take some data as input and display the processed data, often known
as information or results, on a suitable medium.
• One method is to assign values to variables through the assignment statements such
as x=5; a=0; and so on.
• Another method is to use the input and out function scanf which can read data from
a keyboard.
• For outputting results we have used extensively the function printf which sends
results out to a terminal.
• Each program that uses a standard input/output function must contain the
statement #include <stdio.h> at the beginning.
Reading a Character
• The simplest of all managing input and output operations in C is
reading a character from the ‘standard input’ unit (usually the
keyboard) and writing it to the ‘standard output’ unit (usually the
screen).
• Reading a single character can be done by using the function getchar.
variable_name=grtchar();
• variable_name is a valid C name that has been declared as char type.
• When this statement is encountered, the computer waits until a key is
pressed and then assigns this character as a value to getchar function.
• Since getchar is used on the right hand side of an assignment
statement, the character value of getchar is in turn assigned to the
variable name on the left.
char name;
name = getchar();
• Will assign the character ‘H’ to the variable name when we press the
key H on the keyboard.
• Since getchar is a function, it requires a set of parentheses as shown.
What will be the output?
#include <stdio.h>
int main()
{
char answer;
printf("Would you like to know my name?\n");
printf("Type Y for YES and N for NO: ");
answer = getchar(); /* .... Reading a character...*/
if(answer == 'Y' || answer == 'y')
printf("\n\nMy name is BUSY BEE\N");
else
printf("\n\nYou are good for nothing\n");
return 0;
}
What will be the output?
#include <stdio.h>
#include <ctype.h>
int main()
{
char character;
printf("Press any key\n");
character = getchar();
if (isalpha(character) >0)/* Test for letter */
printf("The character is a letter.");
else if (isdigit (character) >0)/* Test for digit */
printf("The character is a digit is a digit.");
else
printf("The character is not alphanumeric.");
return 0;
}
Writing a Character
• Like getchar, there is an analogous function putchar for writing characters
one at a time to the terminal. It takes the form as shown below:
putchar (variable_name);
• where variable_name is a type char variable containing a character.
• This statement display the character contained in the variable_name at the
terminal.
answer = 'Y' ;
putchar (answer);
• will display the character Y on the screen.
• The statement putchar (‘\n’); would cause the cursor on the screen to
move to the beginning of the next line.
What will be the output?
#include <stdio.h>
#include <ctype.h>
int main()
{
char character;
printf(“Enter an alphabet\n");
putchar(‘\n’); /*move to next line */
character = getchar();
if (islower(character))
putchar(toupper(character)); /* Reverse and display */
else
putchar(tolower(character)); /* Reverse and display */
return 0;
}
Formatted Input
• Formatted input refers to an input data that has been arranged in a
particular format.
• For example, consider the following data: 15.75 123 John
• This line contains three pieces of data, arranged in a particular form.
• Such data has to be read conforming to the format of its appearance.
• For example, the first part of the data should be read into a variable
float, the second into int, and the third part into char.
• This is possible in C using the scanf function. (scanf means scan
formatted)
• The general form of scanf is
scanf(“Control string”,arg1, arg2,…argn);
• The control string specifies the field format in which the data is to be
entered and the argument arg1, arg2,… argn specify the address of
locations where the data is stored.
• Control string and arguments are separated by commas.
• Control string contains field specifications, which direct the
interpretation of input data.
• It may include:
• Field (or format) specifications, consisting of the conversion character % a
data type character (or type specifier), and an optional number, specifying the
field width.
• Blanks, tabs, or newlines.
• Blanks, tabs and newlines are ignored.
• The data type character indicates the type of data is to be assigned to
the variable associated with the corresponding argument.
• The field width specifier is optional.
Inputting Integer Numbers
• The field specification for reading an integer number is : % w d
• The percentage sign (%) indicates that a conversion specification
follows.
• w is an integer number that specified the field width of the number
to be read and d, know as data type character, indicates that the
number to be read is in integer mode.
• Consider the following example: scanf (“%2d %5d”, &num1, &num2);
• Data line: 50 31426
• The value 50 is assigned to num1 and 31426 is assigned to num2
• Suppose the input data is as follows:
31426 50
• The variable num1 will be assigned 31 (because of %2d) and num2
will be assigned 426 (unread part of 31426).
• The value 50 that is unread will be assigned to the first variable in the
next scanf call.
• This kind of error may be eliminated if we use the field specifications
without the without the field width specifications.
• That is the statement scanf(“%d %d”, &num1, &num2); will read the
data 31426 50 correctly and assign 31426 to num1 and 50 to num2.
• Input data items must be separated by spaces, tabs or newlines,
punctuation marks do not count as separators.
• When the scanf function searches the input data line for a value to be
read, it will always bypass any white space characters.
• What happens if we enter a floating point number of an integer? The
fractional part may be stripped away! Also, scanf may skip reading
further input.
• An input field may be skipped by specifying * in the place of field
width.
• For example, the statement scanf(“%d %*d %d”,&a,&b); will assign
the 123 456 789 as follows 123 to a 456 skipped (because of *) 789 to
b.
• What will be the output?
#include<stdio.h>
int main()
{
int a,b,c,x,y,z;
int p,q,r;
printf(“Enter three integers:\n”);
scanf(“%d %*d %d”,&a, &b, &c);
printf(“%d %d %d \n\n”,a,b,c);
printf(“Enter two 4-digit integers:\n”);
scanf(“%2d %4d”,&x, &y);
printf(“%d %d \n\n”,x,y);
printf(“Enter two integers:\n”);
scanf(“%d %d”,&a, &x);
printf(“%d %d \n\n”,a,x);
printf(“Enter two 9-digit integers:\n”);
scanf(“%3d %4d %3d”,&p, &q, &r);
printf(“%d %d %d \n\n”,p,q,r);
printf(“Enter two 3-digit integers:\n”);
scanf(“%d %d”,&x, &y);
printf(“%d %d \n\n”,x,y);
return 0;
}
Inputting Real Numbers
• Unlike integer numbers, the field width of real numbers is not to be
specified and therefore scanf reads real numbers using the simple
specification %f for both notation, namely, decimal point notation and
exponential.
• scanf(“%f %f %f”, &x, &y, &z); with the input data 475.89 43.21E-1 678
• will assign the value 475.89 to x, 4.321 to y, and 678.0 to z.
• The input field specifications may be separated by any arbitrary blank
spaces.
• If the number to be read is of double type, the specification should be %if
instead of simple %f.
• A number may be skipped using %*f specification.
Inputting Character Strings
• We have already seen how a single character can be read from the
terminal using the getchar function.
• The same can be achieved using the scanf function also.
• In addition, a scanf function can input strings containg more than one
character.
• Following are the specifications for reading character strings: %ws or
%wc
• The corresponding argument should be a pointer to a character array.
• However, %c may be used to read a single character when the
argument is a pointer to a char variable.
• The address operator need not be specified while we input strings.
• Example : scanf (“%c %s”, &ch, name):
• Here suppose the input given is
a Robert
a is assigned to ch
name will be assigned to Robert.
Reading Mixed Data Types
• It is possible to use one scanf statement to input a data line containing mixed mode
data.
• In such cases care should be exercised to ensure that the input data items match
the control specifications in order and type.
• When an attempt is made to read an item that does not match the type expected,
the scanf function does not read any further and immediately returns the value
read.
• The statement scanf ("%d %c %f %s", &count, &code, &ratio, name); will read the
data 15 p 1.575 coffee
• correctly and assign the values to the variables in the order in which they appear.
• Some systems accept integers in the place of real numbers and vice versa, and the
input data is converted to the type specification in the control string.
Detection of Errors in Input
• When a scanf function completes reading its, it returns the value of
number of items that are successfully read.
• This value can be used to test whether any errors occurred in reading
the input.
• For example the statement scanf("%d %f %s, &a, &b, name); will
return the value 3 if the following data is typed in: 20 150.25 motor
and will return the value 1 if following line is entered 20 motor
150.25
• This is because the function would encounter a string when it was
expecting a floating point value, and would therefore terminate its
scan after reading the first value.
Points to Remember While Using scanf
• All function arguments, except the control string must be pointers to variables.
• Format specifications contained in the control string should match the arguments
in order.
• Input data items must be separated by spaces and must match the variables
receiving the input in the same order.
• The reading will be terminated, when scanf encounters a ‘mismatch’ of data or a
character that is not valid for value being read.
• When searching for a value, scanf ignores line boundaries and simply looks for
the next appropriate character.
• Any unread data items in a line be considered as part of the data input to the
next scanf call.
• When the field width specifier w is used, it should be large enough to contain the
input data size.
Formatted Output
• The general form of printf statement is:
printf(“Control string”, arg1,arg2,…argn);
• Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of
each item
3. Escape sequence characters such as \n, \t
• Some examples of printf:
printf(“Programming in C”);
printf(“ ”);
printf(“\n”);
printf(“%d”,x);
printf(“a = %f \n b = %f”,a,b);
printf(“sum = %d”,1234);
printf(“\n\n”);
Output of Integer Numbers
• The format specification for printing an integer number is %wd where
w specifies the minimum field width for the output.
• However, if a number is greater than the specified field width, it will
be printed in full, overriding the minimum specification.
• d specifies that the value to be printed is an integer.
Format Output
printf("%d",9876); 9 8 7 6
printf("%6d",9876); 9 8 7 6
printf("%2d",9876); 9 8 7 6
printf("%-6d",9876); 9 8 7 6
printf("%06d",9876); 0 0 9 8 7 6
Output of Real Numbers
• The output of real number may be displayed in decimal notation
using the following format specification
%w.p f
• The integer w indicates the minimum number of positions that are to
be used for the display of the value and the integer p indicates the
number of digits to be displayed after the decimal point(precision).
• The value, when displayed, is rounded to p decimal places and
printed right justified in the field of w columns.
• Leading blanks and trailing zeros will appear as necessary.
• The following examples illustrate the output of the number y =
98.7654
Format Output
printf("%7.4f",y) 9 8 . 7 6 5 4
printf("%7.2f",y) 9 8 . 7 7
printf("%-7.2f",y) 9 8 . 7 7
printf("%f",y) 9 8 . 7 6 5 4
printf("%10.2e",y) 9 . 8 8 e + 0 1
printf("%11.4e",-y) - 9 . 8 7 6 5 e + 0 1
printf("%-10.2e",y) 9 . 8 8 e + 0 1
printf("%e",y) 9 . 8 7 6 5 4 0 e + 0 1
Printing of a single character
• A single character can be displayed in a desired position using format:
%wc
• The character will be displayed right justified in the field of w columns
• We can make the left justified by placing a minus sign before the
integer w.
• The default value of w is 1.
Printing of strings
• The format specification for outputting strings is similar to that of real
numbers.
• It is of the form
%w.ps
• Where w specifies the field width for display and p instructs that only
the first p characters of the string are to be displayed.
• The display is right justified.
• The following examples show the effect of variety of specifications in
printing a string “NEW DELHI 110001”, containing 16
characters(including blanks)

Specification Output

1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0

%s N E W D E L H I 1 1 0 0 0 1

%20s N E W D E L H I 1 1 0 0 0 1

%20.10s N E W D E L H I

%.5s N E W D

%-20.10s N E W D E L H I

%5s N E W D E L H I 1 1 0 0 0 1
Mixed Data Output
• It is permitted to mix data types in one printf.
• For example, the statement of the type
printf(“%d %f %s %c”,a,b,c,d);
Is valid.
• The format specification should match the variable in number, order,
and type.
• If there are not enough variables or if they are of wrong type, the
output results will be incorrect.
Try out the following:
#include<stdio.h>
int main()
{
int m = 12345;
float y = 98.7654;
char x = 'A';
char name[20] = "NIT MEGHALAYA";
printf("%d\n",m);
printf("%10d\n",m);
printf("%010d\n",m);
printf("%-10d\n",m);
printf("%7.4f\n",y);
printf("%f\n",y);
printf("%7.2f\n",y);
printf("%-7.2f\n",y);
printf("%07.2f\n",y);
printf("%c\n%3c\n%5c\n",x,x,x);
printf("%3c\n%c\n",x,x);
printf("%s\n",name);
printf("%20s\n",name);
printf("%20.10s\n",name);
printf("%.5s\n",name);
printf("%-20.10s\n",name);
printf("%5s\n",name);
return 0;
}

You might also like