You are on page 1of 19

Dale Roberts

Basic I/O Basic I/O - - printf() printf()


CSCI 230
Department of Computer and Information Science,
SchooI of Science, IUPUI
Dale Roberts, Dale Roberts, 0ctur0r 0ctur0r
Department of Computer and nformation Science Department of Computer and nformation Science
UPU UPU
Dale Roberts
ormatted Input/Output ormatted Input/Output
In this chapter In this chapter
Presentation of results Presentation of results
scanf scanf and and printf printf
Streams (input and output) Streams (input and output)
gets gets, , puts puts, , getchar getchar, , putchar putchar (in (in <stdio.h> <stdio.h>) )
Streams Streams
Sequences of characters organized into lines Sequences of characters organized into lines
Each line consists of zero or more characters and ends with Each line consists of zero or more characters and ends with
newline character newline character
ANS C must support lines of at least 254 characters ANS C must support lines of at least 254 characters
Performs all input and output Performs all input and output
Can often be redirected Can often be redirected
Standard input Standard input keyboard keyboard
Standard output Standard output screen screen
Standard error Standard error screen screen
Dale Roberts
ormatting Output with ormatting Output with printf printf
printf printf
Precise output formatting Precise output formatting
Conversion specifications: flags, field Conversion specifications: flags, field
widths, precisions, etc. widths, precisions, etc.
Can perform rounding, aligning columns, Can perform rounding, aligning columns,
right/left justification, inserting literal right/left justification, inserting literal
characters, exponential format, hexadecimal characters, exponential format, hexadecimal
format, and fixed width and precision format, and fixed width and precision
Dale Roberts
ormatting Output with ormatting Output with printf printf cont.) cont.)
ormat ormat
printf format-controI-string, other-
arguments
ormat control string: describes output format, ormat control string: describes output format,
Ordinary characters: copy to output stream: Ordinary characters: copy to output stream: printf(this is printf(this is
an output an output\ \n); n);
Conversion specifications: leading with character '%' Conversion specifications: leading with character '%'
ormat: ormat:
% %- -w.plx w.plx
[ [- -]: ]: optional optional left justification, if exists left justification, if exists
[w]: [w]: optional optional minimal width (wider if necessary). The minimal width (wider if necessary). The
padding character is padding character is blank normally and zero if the field blank normally and zero if the field
width was specified with a leading zero width was specified with a leading zero
[.]: [.]: optional optional separates field w and p separates field w and p
Dale Roberts
ormatting Output with ormatting Output with printf printf cont.) cont.)
[p]: [p]: optional optional maximum field width for a string maximum field width for a string precision precision
of floating number of floating number
[l]: [l]: long integer long integer
[x]:d [x]:d decimal signed integer decimal signed integer
i i decimal signed integer (the decimal signed integer (the d d and and i i specifiers are specifiers are
different when used different when used in in scanf scanf) )
u u decimal unsigned integer decimal unsigned integer
x x hexadecimal unsigned integer ( hexadecimal unsigned integer (0 0 - - 9 9 and and a a - - f f) )
X X unsigned hexadecimal integer unsigned hexadecimal integer ( (0 0 - - 9 9 and and A A - - F F) )
h h or or l l length modifiers; length modifiers; place before any integer place before any integer
conversion specifier to conversion specifier to indicate that a indicate that a short short or or
long long integer is displayed respectively integer is displayed respectively
Dale Roberts
h h or or l l length modifiers; length modifiers; place before any integer place before any integer
conversion specifier to conversion specifier to indicate that a indicate that a short short or or
long long integer is displayed respectively integer is displayed respectively
o o octal unsigned integer octal unsigned integer
f f floating pointer number floating pointer number
g g either either f f or or e e, whichever is shorter , whichever is shorter
c c single character single character
s s character string character string
e e exponential floating pointer number exponential floating pointer number
Other Other- -arguments: correspond to each conversion specification in arguments: correspond to each conversion specification in
format format- -control control- -string, such as variables. string, such as variables.
Dale Roberts
1 /* Fig 9.2: fig09_02.c */
2 /* Using the integer conversion specifiers */
3 #include <stdio.h>
4
5 main()
6 {
7 printf( "%d\n", 455 );
8 printf( "%i\n", 455 ); /* i same as d in
printf */ 9 printf( "%d\n", +455 );
10 printf( "%d\n", -455 );
11 printf( "%hd\n", 32000 );
12 printf( "%ld\n", 2000000000 );
13 printf( "%o\n", 455 );
14 printf( "%u\n", 455 );
15 printf( "%u\n", -455 );
16 printf( "%x\n", 455 );
17 printf( "%X\n", 455 );
18
19
20 }
455
455
455
-455
32000
2000000000
707
455
65081
1c7
1C7
Example:
Printing Integers Printing Integers
WhoIe number no decimaI point): 25, 0, -9
Positive, negative, or zero
OnIy minus sign prints by defauIt
Program
Output
Dale Roberts
Printing Ioating Printing Ioating- -Point Numbers Point Numbers
Ioating Point Number Ioating Point Number
ave a decimal point ( ave a decimal point (33.5 33.5) )
Exponential notation Exponential notation
(computer's version of (computer's version of
scientific notation) scientific notation)
150.3 150.3 is is 1.503 x 10 1.503 x 10
in scientific in scientific
150.3 150.3 is is 1.503E+02 1.503E+02 in in
exponential ( exponential (%E %E stands for stands for
exponent) exponent)
Can use Can use %e %e or or %E %E
f f : : print floating point with print floating point with
at least one digit to left of at least one digit to left of
decimal decimal
g g (or (or G G) : prints in ) : prints in f f or or e e
with no trailing zeros with no trailing zeros
( (1.2300 1.2300 becomes becomes 1.23 1.23) )
Use exponential if exponent Use exponential if exponent
less than less than - -4 4, or greater than , or greater than
or equal to precision ( or equal to precision (6 6 digits digits
by default) by default)
1 /* Fig 9.4: fig09_04.c */
2 /* Printing floating-point numbers with
3 floating-point conversion specifiers */
4
5 #include <stdio.h>
6
7 int main()
8 {
9 printf( "%e\n", 1234567.89 );
10 printf( "%e\n", +1234567.89 );
11 printf( "%e\n", -1234567.89 );
12 printf( "%E\n", 1234567.89 );
13 printf( "%f\n", 1234567.89 );
14 printf( "%g\n", 1234567.89 );
15 printf( "%G\n", 1234567.89 );
16
17 return 0;
18 }
1.234568e+006
1.234568e+006
-1.234568e+006
1.234568E+006
1234567.890000
1.23457e+006
1.23457E+006
Example:
Program Output
Dale Roberts
Printing Strings and Characters Printing Strings and Characters
%c %c
Prints Prints char char argument argument
Cannot be used to print Cannot be used to print
the first character of a the first character of a
string string
%s %s
Requires a pointer to Requires a pointer to
char char as an argument as an argument
(line 8) (line 8)
Cannot print a Cannot print a char char
argument argument
Prints characters until Prints characters until
NULL NULL ( (' '\ \0' 0') )
encountered encountered
Single quotes for Single quotes for
character constants character constants
( ('z' 'z') )
Double quotes for strings Double quotes for strings
"z" "z" (which actually (which actually
contains two characters, contains two characters,
'z' 'z' and and ' '\ \0' 0') )
1 /* Fig 9.5: fig09_05c */
2 /* Printing strings and characters */
3 #include <stdio.h>
4
5 int main()
6 {
7 char character = 'A';
8 char string[] = "This is a string";
9 const char *stringPtr = "This is also a
string"; 10
11 printf( "%c\n", character );
12 printf( "%s\n", "This is a string" );
13 printf( "%s\n", string );
14 printf( "%s\n", stringPtr );
15
16 return 0;
17 }
A
This is a string
This is a string
This is also a
string
Program Output
Example:
Dale Roberts
Other Conversion Specifiers Other Conversion Specifiers
%p %p
Displays pointer value (address) Displays pointer value (address)
%n %n
Stores number of characters already output by current Stores number of characters already output by current printf printf
statement statement
Takes a pointer to an integer as an argument Takes a pointer to an integer as an argument
Nothing printed by a Nothing printed by a %n %n specification specification
Every Every printf printf call returns a value call returns a value
Number of characters output Number of characters output
Negative number if error occurs Negative number if error occurs
%% %%
Prints a Prints a percent percent sign sign
Dale Roberts
1 /* Fig 9.7: fig09_07.c */
2 /* Using the p, n, and % conversion specifiers */
3 #include <stdio.h>
4
5 int main()
6 {
7 int *ptr;
8 int x = 12345, y;
9
10 ptr = &x;
11 printf( "The value of ptr is %p\n", ptr );
12 printf( "The address of x is %p\n\n", &x );
13
14 printf( "Total characters printed on this line is:%n",
&y ); 15 printf( " %d\n\n", y );
16
17 y = printf( "This line has 28 characters\n" );
18 printf( "%d characters were printed\n\n", y );
19
20 printf( "Printing a %% in a format control string\n" );
21
22 return 0;
23 }
The value of ptr is 0065FDF0
The address of x is 0065FDF0
Total characters printed on this line is: 41
This line has 28 characters
28 characters were printed
Printing a % in a format control string
Example:
Program Output
Dale Roberts
Printing with ieId Widths and Precisions Printing with ieId Widths and Precisions
ieId width ieId width Size of fieId in which data is printed)
f width larger than data, default right justified f width larger than data, default right justified
f field width too small, increases to fit data f field width too small, increases to fit data
Minus sign uses one character position in field Minus sign uses one character position in field
nteger width inserted between nteger width inserted between % % and conversion specifier. and conversion specifier. Example Example: :
%4d %4d : : field width of field width of 4 4
Precision Precision eaning varies depending on data type)
ntegers (default ntegers (default 1 1): Minimum number of digits to print, f data too small, ): Minimum number of digits to print, f data too small,
prefixed with zeros prefixed with zeros
loating point: Number of digits to appear after decimal ( loating point: Number of digits to appear after decimal (e e and and f f). ).
g g : : maximum number of significant digits maximum number of significant digits
Strings: Maximum number of characters to be written from string Strings: Maximum number of characters to be written from string
ormat: Use a dot ( ormat: Use a dot (. .) then precision number after ) then precision number after % %
Example Example: %.3f : %.3f
Dale Roberts
Printing with ieId Widths and Precisions Printing with ieId Widths and Precisions cont) cont)
ieId width and precision ieId width and precision
Can both be specified using format of Can both be specified using format of
%width.precision %width.precision
Example: Example: %5.3f %5.3f
Negative field width ( Negative field width ( ): left justified; Positive field ): left justified; Positive field
width: right justified width: right justified
Precision must be positive Precision must be positive
Can use integer expressions to determine field width Can use integer expressions to determine field width
and precision values and precision values
Place an asterisk ( Place an asterisk (* *) in place of the field width or precision ) in place of the field width or precision
Matched to an Matched to an int int argument in argument list argument in argument list
Example Example: : printf( "%*.*f", 7, 2, 98.736 ); printf( "%*.*f", 7, 2, 98.736 );
Dale Roberts
1 /* Fig 9.9: fig09_09.c */
2 /* Using precision while printing integers,
3 floating-point numbers, and strings */
4 #include <stdio.h>
5
6 int main()
7 {
8 int i = 873;
9 double f = 123.94536;
10 char s[] = "Happy Birthday";
11
12 printf( "Using precision for integers\n" );
13 printf( "\t%.4d\n\t%.9d\n\n", i, i );
14 printf( "Using precision for floating-point numbers\n" );
15 printf( "\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f );
16 printf( "Using precision for strings\n" );
17 printf( "\t%.11s\n", s );
18
19 return 0;
20 }
Using precision for integers
0873
000000873
Using precision for floating-point numbers
123.945
1.239e+02
124
Using precision for strings
Happy Birth
/* Initialize variables */
/* print */
Example:
Program Output:
Dale Roberts
Using Iags in the Using Iags in the printf printf ormat ormat- -ControI String ControI String
Iags Iags
Supplement formatting capabilities Supplement formatting capabilities
Place flag immediately to the right of percent sign Place flag immediately to the right of percent sign
Several flags may be combined Several flags may be combined
Iag Description
- minus sign) Left justify the output within the specified fieId.
+ pIus sign) DispIay a pIus sign preceding positive vaIues and a minus sign preceding negative
vaIues.
spac0 Print a space before a positive vaIue not printed with the + fIag
#
Prefix 0 to the output vaIue when used with the octaI conversion specifier
Prefix 0x or 0X to the output vaIue when used with the hexadecimaI conversion
specifiers x or X
orce a decimaI point for a fIoating point number printed with e, E, f, g, or G
that does not contain a fractionaI part. NormaIIy the decimaI point is onIy printed
if a digit foIIows it.) or g and G specifiers, traiIing zeros are not eIiminated.
0 zero) Pad a fieId with Ieading zeros
Dale Roberts
1 /* Fig 9.11: fig09_11.c */
2 /* Right justifying and left justifying values */
3 #include <stdio.h>
4
5 int main()
6 {
7 printf( "%10s%10d%10c%10f\n\n", "hello", 7,
'a', 1.23 );
8 printf( "%-10s%-10d%-10c%-10f\n", "hello", 7,
'a', 1.23 );
9 return 0;
10 }
?????
hello
?????????
7
?????????
a
??
1.230000
hello
?????
7
?????????
a
?????????
1.230000
??
Example:
Program Output:
Dale Roberts
1 /* Fig 9.14: fig09_14.c */
2 /* Using the # flag with conversion
specifiers 3 o, x, X and any floating-point
specifier */ 4 #include <stdio.h>
5
6 int main()
7 {
8 int c = 1427;
9 double p = 1427.0;
10
11 printf( "%#o\n", c );
12 printf( "%#x\n", c );
13 printf( "%#X\n", c );
14 printf( "\n%g\n", p );
15 printf( "%#g\n", p );
16
17 return 0;
18 }
02623
0x593
0X593
1427
1427.00
xampIe:
Program Output:
Dale Roberts
Example Example::
int i=1256; int i=1256;
printf(%d,i); printf(%d,i); 4 characters 4 characters 1256 1256
printf(%5d,i); printf(%5d,i); 5 characters 5 characters
? ?
1256 1256
printf(%05d,i); printf(%05d,i); 5 characters 5 characters 01256 01256
printf(%x,i); printf(%x,i); 3 characters 3 characters 788 788
printf(% printf(%- -5d,i); 5d,i); 5 characters 5 characters 1256 1256
? ?
Example Example::
float buf=125.12; float buf=125.12;
printf(%f,buf); printf(%f,buf); 125.119995 125.119995 (floating number (floating number
precision error) precision error)
printf(%.0f,buf); printf(%.0f,buf); 125 125
printf(%7.2f,buf); printf(%7.2f,buf);
? ?
125.12 125.12
printf(%07.2f,buf); printf(%07.2f,buf); 0125.12 0125.12
Example Example: :
char buf[] = hello, char buf[] = hello, world; world;
printf(%10s,buf); printf(%10s,buf); hello, world hello, world
printf(% printf(%- -10s,buf); 10s,buf); hello, world hello, world
printf(%20s,buf); printf(%20s,buf);
???????? ????????
hello, world hello, world
printf(%20.10s,buf); printf(%20.10s,buf);
?????????? ??????????
hello, wor hello, wor
printf(% printf(%- -20.10s,buf); 20.10s,buf); hello, wor hello, wor
?????????? ??????????
printf(%.10s,buf); printf(%.10s,buf); hello, wor hello, wor
Dale Roberts
Printing LiteraIs and scape Sequences Printing LiteraIs and scape Sequences
Printing LiteraIs Printing LiteraIs
Most characters can be printed Most characters can be printed
Certain "problem" characters, such as the quotation mark " Certain "problem" characters, such as the quotation mark "
Must be represented by escape sequences Must be represented by escape sequences
Represented by a backslash Represented by a backslash \ \ followed by an escape character followed by an escape character
%abIe of aII escape sequences %abIe of aII escape sequences
scape sequence Description
\ \' ' Output the singIe quote ) character.
\ \ Output the doubIe quote ) character.
\ \? ? Output the question mark ) character.
\ \\ \ Output the backsIash ) character.
\ \a a Cause an audibIe beII) or visuaI aIert
\ \b b ove the cursor back one position on the current Iine.
\ \f f ove the cursor to the start of the next IogicaI page.
\ \n n ove the cursor to the beginning of the next Iine.
\ \r r ove the cursor to the beginning of the current Iine.
\ \t t ove the cursor to the next horizontaI tab position
\ \v v ove the cursor to the next verticaI tab position.

You might also like