Society & Lifestyle
|Computing||Share This Page|
Managing Output Operations
|by Sachin Mehta|
Last time, we had a brief look on the input operations in C language. Naturally, the logical following to it will be managing the output operations. This section will tell you the proper ways to display output so that it will be presented in an acceptable form to the user.
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 :
where variable_name is a type char variable containing a character. This statement displays the character contained in the variable_name at the terminal. For example, the statements
will display the character Y to the screen.
It is highly desirable that the outputs are produced in such a way that they are understandable and are in an easy-to-use form. The printf statement provides certain features that can be effectively exploited to control the alignment and spacing of printouts on the terminals. The general form of printf statement is:
Control string consists of three types of items:
The control string indicates how many arguments follow and what their types are. The arguments arg1 ,arg2 , ...argn are the variables whose values are formatted and printed according to the specifications of the control string. The arguments should match in number , order and type with the format specifications .
Output of Integer Numbers
The format specification for printing an integer number is % w d
where w specifies the minimum field width for the output . However , if a number is greater than the specified width , it will be printed in full , overriding the minimum specification . d specifies that the value to be printed is an integer. The number is written right-justified in the given field width. Leading blanks will appear as necessa- ry.
Output of Real Numbers
The output of a real number may be displayed in decimal notation using the following format:
% 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. 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 default precision is 6 decimal places.
Printing of strings
The format specification for outputting strings is similar to that of real numbers. It is of the form
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.
Printf format codes are same as that for scanf , with the meaning of each associated with printing.( %[..] not applicable).
|More by : Sachin Mehta|
|Views: 2072 Comments: 0|
|Top | Computing|