0% found this document useful (0 votes)
30 views33 pages

05 Formatted Input Output

Uploaded by

Destiny
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)
30 views33 pages

05 Formatted Input Output

Uploaded by

Destiny
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/ 33

Formatted Input/Output

CEN116 Algorithms and Programming II


Streams
• Input and output are performed with sequences of bytes called
streams:
• In input operations, the bytes flow into main memory from a
device, such as a keyboard, a solid-state drive, a network
connection, and so on.
• In output operations, bytes flow from main memory to a device,
such as a computer’s screen, a printer, a solid-state drive, a
network connection, and so on.
Streams
• When program execution begins, the program has access to three
streams:
• the standard input stream, which is connected to the keyboard,
• the standard output stream, which is connected to the screen, and
• the standard error stream, which also is connected to the screen.
Formatting Output With printf
• Every printf call contains a format control string that describes the output
format
• The format control string consists of conversion specifiers, flags, field widths,
precisions and literal characters
• Together with the percent sign (%), these form conversion specifications:
• Rounding floating-point values to an indicated number of decimal places
• Aligning columns of numbers at their decimal points
• right-aligning and left-aligning outputs
• Inserting literal characters at precise locations in a line of output
• Representing floating-point numbers in exponential format
• Representing unsigned integers in octal and hexadecimal format
• Displaying data with fixed-size field widths and precisions
Printing Integers
• Integer values are displayed in one of several formats described by
the following integer conversion specifiers
Conversion specifier Description
d Display as a signed decimal integer.
i Display as a signed decimal integer.
o Display as an unsigned octal integer.
u Display as an unsigned decimal integer.
x or X Display as an unsigned hexadecimal integer. X uses the digits 0-9
and the uppercase letters A-F, and x uses the digits 0-9 and the
lowercase letters a-f.
h, l or ll (letter “ell”) These length modifiers are placed before any integer conversion
specifier to indicate that the value to display is a short, long or long
long integer.
Printing Integers
1. // Using the integer conversion specifiers
2. #include <stdio.h>
3.
4. int main(void) {
5. printf("%d\n", 455);
6. printf("%i\n", 455); // i same as d in printf
7. printf("%d\n", +455); // plus sign does not print
8. printf("%d\n", -455); // minus sign prints
9. printf("%hd\n", 32000); // print as type short
10. printf("%ld\n", 2000000000L); // print as type long
11. printf("%o\n", 455); // octal
12. printf("%u\n", 455);
13. printf("%u\n", -455);
14. printf("%x\n", 455); // hexadecimal with lowercase letters
15. printf("%X\n", 455); // hexadecimal with uppercase letters
16.}
Printing Integers
Output:
455
455
455
-455
32000
2000000000
707
455
4294966841
1c7
1C7
Printing Floating-Point Numbers
• Floating-point values contain a decimal point and are displayed using
the conversion specifiers summarized below.
Conversion specifier Description

e or E Display a floating-point value in exponential notation.

f or F Display floating-point values in fixed-point notation.

g or G Display a floating-point value in either the fixed-point form f or the


exponential form e (or E), based on the value’s magnitude.
L Place this length modifier before any floating-point conversion specifier
to indicate that a long double floating-point value should be displayed.
Printing Floating-Point Numbers
• Exponential Notation
• The conversion specifiers e and E display floating-point values in
exponential notation—the computer equivalent of scientific
notation used in mathematics
• The value 150.4582 is represented in scientific notation as
1.504582 × 102
• and in exponential notation as
• 1.504582E+02
• In this notation, the E stands for “exponent” and indicates that
1.504582 is multiplied by 10 raised to the second power (E+02)
Conversion Specifiers e, E and f
• Values displayed with the conversion specifiers e, E and f show six
digits of precision to the decimal point’s right by
• Conversion specifier f always prints at least one digit to the left of the
decimal point, so fractional values will be preceded by "0"
• Conversion specifiers e and E precede the exponent with lowercase e
or uppercase E
• Each prints exactly one digit to the decimal point’s left
Conversion Specifiers g and G
• Conversion specifier g (or G) prints in e (E) or f format with no trailing zeros
• g uses the e (E) format if, after conversion to exponential notation, the value’s
exponent is less than -4 or the exponent is greater than or equal to the
specified precision
• Otherwise, g uses the conversion specifier f to print the value
• The default precision is 6 significant digits for g and G—a maximum of 6 digits
will display
• Precision
• For g and G, the precision indicates the maximum number of significant digits
to display, including the digit to the left of the decimal point
• For exponential notation, g and G precede the exponent with a lowercase e or
uppercase E
Demonstrating Floating-Point Conversion
Specifiers
1. // Using the floating-point conversion specifiers
2. #include <stdio.h>
3.
4. int main(void) {
5. printf("%e\n", 1234567.89);
6. printf("%e\n", +1234567.89); // plus does not print
7. printf("%e\n", -1234567.89); // minus prints
8. printf("%E\n", 1234567.89);
9. printf("%f\n", 1234567.89); // six digits to right of
decimal point
10. printf("%g\n", 1234567.89); // prints with lowercase e
11. printf("%G\n", 1234567.89); // prints with uppercase E
12.}
Demonstrating Floating-Point Conversion
Specifiers
Output:
1.234568e+06
1.234568e+06
-1.234568e+06
1.234568E+06
1234567.890000
1.23457e+06
1.23457E+06
Printing Strings and Characters
• The c and s conversion specifiers are used to print individual characters and
strings
• Conversion specifier c requires a char argument
• Conversion specifier s requires a char* as an argument and prints characters
until a terminating null is encountered
• If the string does not have a null terminator, the result is undefined—
printf will either continue printing until it encounters a zero byte or the
program will terminate prematurely (i.e., “crash”) and indicate a
“segmentation fault” or “access violation” error
• The program in the next example displays characters and strings with conversion
specifiers c and s
Printing Strings and Characters
1. // Using the character and string conversion specifiers
2. #include <stdio.h>
3.
4. int main(void) {
5. char character = 'A'; // initialize char
6. printf("%c\n", character);
7.
8. printf("%s\n", "This is a string");
9.
10. char string[] = "This is a string"; // initialize char array
11. printf("%s\n", string);
12.
13. const char *stringPtr = "This is also a string"; // char
pointer
14. printf("%s\n", stringPtr);
15.}
Printing Strings and Characters
Output:
A
This is a string
This is a string
This is also a string
Printing Strings and Characters
• Errors in Format Control Strings
• Most compilers do not catch format-control-string errors
• Using %c to print a string is a logic error—%c expects a char argument
• A string is a char *
• Using %s to print a char argument usually causes a fatal execution-time logic
error called an access violation
• The conversion specification %s expects an argument of type pointer to
char, so it treats the char’s numeric value as a pointer
• Such small numeric values often represent memory addresses that are
restricted by the operating system
Printing With Field Widths and Precision
• If a field width is larger than the data being printed, the data will
normally be right-aligned within that field
• An integer representing the field width is inserted between the
percent sign (%) and the conversion specifier (e.g., %4d)
• Values wider than the field still display in full
• A minus sign for a negative value uses a character in the field width
• Field widths can be used with all conversion specifiers
• Not providing a sufficiently large field width to handle a printed value
can offset other data being printed, producing confusing outputs
Field Widths for Integers
1. // Right-aligning integers in a field
2. #include <stdio.h>
3.
4. int main(void) {
5. printf("%4d\n", 1);
6. printf("%4d\n", 12);
7. printf("%4d\n", 123);
8. printf("%4d\n", 1234);
9. printf("%4d\n\n", 12345);
10.
11. printf("%4d\n", -1);
12. printf("%4d\n", -12);
13. printf("%4d\n", -123);
14. printf("%4d\n", -1234);
15. printf("%4d\n", -12345);
16.}
Field Widths for Integers
OUTPUT:
1
12
123
1234
12345

-1
-12
-123
-1234
-12345
Precisions for Integers, Floating-Point
Numbers and Strings
• printf enables you to specify the precision with which data is printed
• Different meanings for different types:
• For integer conversion specifiers, indicates minimum number of
digits to print
• For fewer digits than the specified precision, if the precision
value has a leading zero or decimal point, zeros are prefixed to
the printed value until the total number of digits is equivalent
to the precision. If neither a zero nor a decimal point is present
in the precision value, spaces are inserted instead. The default
precision for integers is 1.
Precisions for Integers, Floating-Point
Numbers and Strings
• For e, E and f, indicates the number of digits to appear after the
decimal point
• For g and G, indicates the maximum number of significant digits to
print
• For s, indicates the maximum number of characters written from
the beginning of the string
• To use precision, place a decimal point (.), followed by an integer
representing the precision between the percent sign and the
conversion specifier
Precisions for Integers, Floating-Point
Numbers and Strings
1. // Printing integers, floating-point numbers and strings
with precisions
2. #include <stdio.h>
3.
4. int main(void) {
5. puts("Using precision for integers");
6. int i = 873; // initialize int i
7. printf("\t%.4d\n\t%.9d\n\n", i, i);
8.
9. puts("Using precision for floating-point numbers");
10. double f = 123.94536; // initialize double f
11. printf("\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f);
12.
13. puts("Using precision for strings");
14. char s[] = "Happy Birthday"; // initialize char array s
15. printf("\t%.11s\n", s);
16.}
Precisions for Integers, Floating-Point
Numbers and Strings
Output:
Using precision for integers
0873
000000873
Using precision for floating-point numbers
123.945
1.239e+02
124
Using precision for strings
Happy Birth
Printing Literals and Escape Sequences
• Literal characters included in the format control string are simply
output by printf
• There are several “problem” characters, such as the quotation mark
(") that delimits the format control string itself
• Various control characters, such as newline and tab, must be
represented by escape sequences
• An escape sequence is represented by a backslash (\), followed by a
particular escape character
Escape sequence Description
\' (single quote) Output the single quote (') character.
\" (double quote) Output the double quote (") character.
\? (question mark) Output the question mark (?) character.
\\ (backslash) Output the backslash (\) character.
\a (alert or bell) Cause an audible (bell) or visual alert (typically, flashing the window in
which the program is running).

\b (backspace) Move the cursor back one position on the current line.
\f (new page or form feed) Move the cursor to the next logical page’s start.

\n (newline) Move the cursor to the beginning of the next line.


\r (carriage return) Move the cursor to the beginning of the current line.
\t (horizontal tab) Move the cursor to the next horizontal tab position.
\v (vertical tab) Move the cursor to the next vertical tab position.
Formatted Input With scanf
• Input formatting can be accomplished with scanf
• Every scanf statement contains a format control string that
describes the format of the data to be input
• Some capabilities include
• Inputting all types of data
• Inputting specific characters from an input stream
• Skipping specific characters in the input stream
scanf Syntax
• Function scanf is written in the following form:
scanf(format-control-string, other-arguments);
• format-control-string describes the input formats
• other-arguments are pointers to variables in which inputs are
stored
• Avoid asking the user to enter many data items in response to a single
prompt
• Always consider what the user and your program will do when
incorrect data is entered
scanf Conversion Specifiers
• The following table summarizes the conversion specifiers used to
input all types of data
• The d and i conversion specifiers have different meanings for input
with scanf but are interchangeable for output with printf
scanf Conversion Specifiers
Conversion specifier Description
d Read an optionally signed decimal integer. The corresponding argument is a
pointer to an int.
i Read an optionally signed decimal, octal or hexadecimal integer. The
corresponding argument is a pointer to an int.
o Read an octal integer. The corresponding argument is a pointer to an
unsigned int.
u Read an unsigned decimal integer. The corresponding argument is a pointer
to an unsigned int.
x or X Read a hexadecimal integer. The corresponding argument is a pointer to an
unsigned int.
h, l and ll Place before any integer conversion specifier to indicate that a short, long or
long long integer is to be input.
scanf Conversion Specifiers
Conversion specifier Description
e, E, f, g or G Read a floating-point value. The corresponding argument is a pointer to a
floating-point variable.
l or L Place before any floating-point conversion specifier to indicate that a
double or long double value is to be input. The corresponding
argument is a pointer to a double or long double variable.
scanf Conversion Specifiers
Conversion specifier Description
c Read a character. The corresponding argument is a pointer to a char; no null
(is added.
s Read a string. The corresponding argument is a pointer to an array of type
char that’s large enough to hold the string and a terminating null
character—which is automatically added.
References
• C How to Program, Ninth Edition by Deitel & Deitel, Pearson, 2022.

You might also like