0% found this document useful (0 votes)
0 views

Week 4 -Formatted InputOutput in C

The document outlines the objectives and content of Week 3 of CENG 110, focusing on formatted input and output in C programming. It covers the use of input and output streams, formatting capabilities for various data types, and the syntax for printf and scanf functions. Key topics include printing integers, floating-point numbers, strings, and characters, as well as using field widths, precision, and formatting flags.

Uploaded by

batam54516
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Week 4 -Formatted InputOutput in C

The document outlines the objectives and content of Week 3 of CENG 110, focusing on formatted input and output in C programming. It covers the use of input and output streams, formatting capabilities for various data types, and the syntax for printf and scanf functions. Key topics include printing integers, floating-point numbers, strings, and characters, as well as using field widths, precision, and formatting flags.

Uploaded by

batam54516
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

CENG 110 – PROGRAMMING AND

COMPUTING II

Week 3 : Formatted InputOutput in C


Objectives
• Use input and output streams
• Use print formatting capabilities
• Use input formatting capabilities
• Print integers, floating-point numbers, strings and
characters
• Print with field widths and precisions
• Use formatting flags in the printf format control string
• Output literals and escape sequences
• Read formatted input using scanf
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Outline (1 of 3)
9.1 Introduction
9.2 Streams
9.3 Formatting Output with printf

9.4 Printing Integers


9.5 Printing Floating-Point Numbers
9.5.1 Conversion Specifiers e, E and f
9.5.2 Conversion Specifiers g and G
9.5.3 Demonstrating Floating-Point Conversion Specifiers
9.6 Printing Strings and Characters
9.7 Other Conversion Specifiers

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Outline (2 of 3)
9.8 Printing with Field Widths and Precision
9.8.1 Field Widths for Integers
9.8.2 Precisions for Integers, Floating-Point Numbers and Strings
9.8.3 Combining Field Widths and Precisions
9.9 printf Format Flags
9.9.1 Right- and Left-Alignment
9.9.2 Printing Positive and Negative Numbers with and without the
+ Flag
9.9.3 Using the Space Flag
9.9.4 Using the # Flag
9.9.5 Using the 0 Flag
9.10 Printing Literals and Escape Sequences

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Outline (3 of 3)
9.11 Formatted Input with scanf
9.11.1 scanf Syntax
9.11.2 scanf Conversion Specifiers
9.11.3 Reading Integers
9.11.4 Reading Floating-Point Numbers
9.11.5 Reading Characters and Strings
9.11.6 Using Scan Sets
9.11.7 Using Field Widths
9.11.8 Skipping Characters in an Input Stream
9.12 Secure C Programming

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.1 Introduction
• Presenting results is an important part of the solution to
any problem
• This chapter discusses printf and scanf formatting
features
• Chapter 11 discusses several additional functions
included in the standard input/output (<stdio.h>)
library

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.2 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.
• 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.
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
9.3 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

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.4 Printing Integers (1 of 4)
• An integer is a whole number, such as 776, 0 or – 52.
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.
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
9.4 Printing Integers (2 of 4)
• Figure 9.1 prints an integer using each integer conversion specifier

• Plus signs do not display by default


• Lines 10–11 use the hd and ld conversion specifiers to display short and
long integer values
– The L suffix on the literal 2000000000L indicates that its type is
long—C treats whole-number literals as int

• Printing a negative value with a conversion specifier that expects an


unsigned value is a logic error
– When line 14 displays −455 with %u, the result is the unsigned
value 4294966841
– A small negative value displays as a large positive integer due to the
value’s “sign bit” in the underlying binary representation.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.4 Printing Integers (3 of 4)
1. // fig09_01.c
2. // Using the integer conversion specifiers
3. #include <stdio.h>
4.
5. int main(void) {
6. printf("%d\n", 455);
7. printf("%i\n", 455); // i same as d in printf
8. printf("%d\n", +455); // plus sign does not print
9. printf("%d\n", -455); // minus sign prints
10. printf("%hd\n", 32000); // print as type short
11. printf("%ld\n", 2000000000L); // print as type long
12. printf("%o\n", 455); // octal
13. printf("%u\n", 455);
14. printf("%u\n", -455);
15. printf("%x\n", 455); // hexadecimal with lowercase letters
16. printf("%X\n", 455); // hexadecimal with uppercase letters
17. }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.4 Printing Integers (4 of 4)
Output:
455
455
455
-455
32000
2000000000
707
455
4294966841
1c7
1C7

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.5 Printing Floating-Point Numbers (1 of 2)

• 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.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.5 Printing Floating-Point Numbers (2 of 2)
• 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  10 2
– 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)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.5.1 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

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.5.2 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

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.5.3 Demonstrating Floating-Point
Conversion Specifiers (1 of 3)

• Figure 9.2 demonstrates each of the floating-point


conversion specifiers
• The %E, %e and %g conversion specifications perform
rounding, but %f does not

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.5.3 Demonstrating Floating-Point
Conversion Specifiers (2 of 3)
1. // fig09_02.c
2. // Using the floating-point conversion specifiers
3. #include <stdio.h>
4.
5. int main(void) {
6. printf("%e\n", 1234567.89);
7. printf("%e\n", +1234567.89); // plus does not print
8. printf("%e\n", -1234567.89); // minus prints
9. printf("%E\n", 1234567.89);
10. printf("%f\n", 1234567.89); // six digits to right of
decimal point
11. printf("%g\n", 1234567.89); // prints with lowercase e
12. printf("%G\n", 1234567.89); // prints with uppercase E
13. }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.5.3 Demonstrating Floating-Point
Conversion Specifiers (3 of 3)
Output:
1.234568e+06
1.234568e+06
-1.234568e+06
1.234568E+06
1234567.890000
1.23457e+06
1.23457E+06

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.6 Printing Strings and Characters (1 of 4)
• 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 Fig 9.3 displays characters and strings with
ure

conversion specifiers c and s

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.6 Printing Strings and Characters (2 of 4)
1. // fig09_03.c
2. // Using the character and string conversion specifiers
3. #include <stdio.h>
4.
5. int main(void) {
6. char character = 'A'; // initialize char
7. printf("%c\n", character);
8.
9. printf("%s\n", "This is a string");
10.
11. char string[] = "This is a string"; // initialize char array
12. printf("%s\n", string);
13.
14. const char *stringPtr = "This is also a string"; // char
pointer
15. printf("%s\n", stringPtr);
16. }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.6 Printing Strings and Characters (3 of 4)
Output:

A
This is a string
This is a string
This is also a string

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.6 Printing Strings and Characters (4 of 4)
• 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

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.7 Other Conversion Specifiers (1 of 3)
• p and % conversion specifiers:
– p—Displays a pointer value in an implementation-defined manner.
– %—Displays the percent character.

• Figure 9.4’s %p prints ptr’s value and x’s address in an implementation-


defined manner, typically using hexadecimal notation
– ptr and x have identical values because line 7 assigns x’s address to
ptr
– The addresses displayed on your system will vary
• The last printf statement uses %% to display the % character
– %% is required because printf normally treats % as the beginning of a
conversion specification
– When % appears in a format control string, it must be followed by a
conversion specifier

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.7 Other Conversion Specifiers (2 of 3)
1. // fig09_04.c
2. // Using the p and % conversion specifiers
3. #include <stdio.h>
4.
5. int main(void) {
6. int x = 12345;
7. int *ptr = &x;
8.
9. printf("The value of ptr is %p\n", ptr);
10. printf("The address of x is %p\n\n", &x);
11.
12. printf("Printing a %% in a format control
string\n");
13.}

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.7 Other Conversion Specifiers (3 of 3)
Output:

The value of ptr is 0x7ffff6eb911c


The address of x is 0x7ffff6eb911c

Printing a % in a format control string

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.8 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)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.8.1 Field Widths for Integers (1 of 3)
• Figure 9.5 prints two groups of five numbers each, right-
aligning those numbers containing fewer digits than the
field width
• 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
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
9.8.1 Field Widths for Integers (2 of 3)
1. // fig09_05.c
2. // Right-aligning integers in a field
3. #include <stdio.h>
4.
5. int main(void) {
6. printf("%4d\n", 1);
7. printf("%4d\n", 12);
8. printf("%4d\n", 123);
9. printf("%4d\n", 1234);
10. printf("%4d\n\n", 12345);
11.
12. printf("%4d\n", -1);
13. printf("%4d\n", -12);
14. printf("%4d\n", -123);
15. printf("%4d\n", -1234);
16. printf("%4d\n", -12345);
17. }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.8.1 Field Widths for Integers (3 of 3)
OUTPUT:
1
12
123
1234
12345

-1
-12
-123
-1234
-12345

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.8.2 Precisions for Integers, Floating-Point
Numbers and Strings (1 of 4)

• 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.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.8.2 Precisions for Integers, Floating-Point
Numbers and Strings (2 of 4)

– 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
• Figure 9.6 demonstrates the use of precision in format
control strings

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.8.2 Precisions for Integers, Floating-Point
Numbers and Strings (3 of 4)
1. // fig09_06.c
2. // Printing integers, floating-point numbers and strings with
precisions
3. #include <stdio.h>
4.
5. int main(void) {
6. puts("Using precision for integers");
7. int i = 873; // initialize int i
8. printf("\t%.4d\n\t%.9d\n\n", i, i);
9.
10. puts("Using precision for floating-point numbers");
11. double f = 123.94536; // initialize double f
12. printf("\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f);
13.
14. puts("Using precision for strings");
15. char s[] = "Happy Birthday"; // initialize char array s
16. printf("\t%.11s\n", s);
17. }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.8.2 Precisions for Integers, Floating-Point
Numbers and Strings (4 of 4)
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

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.8.3 Combining Field Widths and
Precisions
• Combine field width and precision by placing the field width, followed
by a decimal point, followed by a precision between the percent sign
and the conversion specifier
• Can specify field width and precision using integer expressions in the
argument list following the format control string
– Insert an asterisk (*) in place of the field width or precision (or
both)
– The matching int argument in the argument list is evaluated
and used in place of the asterisk
– Field width may be positive (right-align) or negative (left-align)
• printf("%*.*f", 7, 2, 98.736);
– Specifies field width 7, precision 2

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9 printf Format Flags
• printf flags supplement its output formatting capabilities

Flag Description
- (minus sign) Left-align the output within the specified field.

+ Display a plus sign preceding positive values and a minus sign preceding
negative values.
space Print a space before a positive value not printed with the + flag.
# Prefix 0 to the output value when used with the octal conversion specifier o.
#

Prefix 0x or 0X to the output value when used with the hexadecimal conversion
specifiers x or X.
#

Force a decimal point for a floating-point number printed with e, E, f, g or G that


does not contain a fractional part. Normally, the decimal point is printed only if a
digit follows it. For g and G specifiers, trailing zeros are not eliminated.
0 (zero) Pad a field with leading zeros.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.1 Right- and Left-Alignment (1 of 2)
• Flags in a conversion specification are placed
immediately to the right of the % and before the format
specifier
• Flags may be combined in one conversion specifier
• Figure 9.7 demonstrates right-alignment and left-
alignment of a string, an integer, a character and a
floating-point number
• Lines 6 and 8 output lines of numbers representing the
column positions, so you can confirm that the right- and
left-alignment worked correctly

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.1 Right- and Left-Alignment (2 of 2)
1. // fig09_07.c
2. // Right- and left-aligning values
3. #include <stdio.h>
4.
5. int main(void) {
6. puts("1234567890123456789012345678901234567890");
7. printf("%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23);
8. puts("1234567890123456789012345678901234567890");
9. printf("%-10s%-10d%-10c%-10f\n", "hello", 7, 'a', 1.23);
10. }

Output:

1234567890123456789012345678901234567890
hello 7 a 1.230000

1234567890123456789012345678901234567890
hello 7 a 1.230000

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.2 Printing Positive and Negative
Numbers With and Without the + Flag (1 of 2)

• Figure 9.8 prints a positive number and a negative


number, each with and without the + flag
• The plus sign is displayed for positive values only when
the + flag is used

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.2 Printing Positive and Negative
Numbers With and Without the + Flag (2 of 2)
1. // fig09_08.c
2. // Printing positive and negative numbers with and
without the + flag
3. #include <stdio.h>
4.
5. int main(void) {
6. printf("%d\n%d\n", 786, -786);
7. printf("%+d\n%+d\n", 786, -786);
8. }

Output:
786
-786
+786
-786

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.3 Using the Space Flag (1 of 2)
• Figure 9.9 prefixes a space to the positive number with
the space flag
• Useful for aligning positive and negative numbers with
the same number of digits
• The value −547 is not preceded by a space in the
output because of its minus sign.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.3 Using the Space Flag (2 of 2)
1. // fig09_09.c
2. // Using the space flag
3. // not preceded by + or -
4. #include <stdio.h>
5.
6. int main(void) {
7. printf("% d\n% d\n", 547, -547);
8. }

Output:
547
-547

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.4 Using the # Flag (1 of 3)
• Figure 9.10 uses the # flag to prefix 0 to the octal value
and 0x and 0X to the hexadecimal values.
• For g, it forces the decimal point to print.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.4 Using the # Flag (2 of 3)
1. // fig09_10.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(void) {
7. int c = 1427; // initialize c
8. printf("%#o\n", c);
9. printf("%#x\n", c);
10. printf("%#X\n", c);
11.
12. double p = 1427.0; // initialize p
13. printf("\n%g\n", p);
14. printf("%#g\n", p);
15.}

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.4 Using the # Flag (3 of 3)
Output:

02623
0x593
0X593

1427
1427.00

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.5 Using the 0 Flag (1 of 2)
• Figure 9.11 combines the + flag and the 0 (zero) flag to
print 452 in a nine-space field with a + sign and leading
zeros, then prints 452 again using only the 0 flag and a
nine-space field.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.9.5 Using the 0 Flag (2 of 2)
1. // fig09_11.c
2. // Using the 0 (zero) flag
3. #include <stdio.h>
4.
5. int main(void) {
6. printf("%+09d\n", 452);
7. printf("%09d\n", 452);
8. }

Output:
+00000452
000000452
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
9.10 Printing Literals and Escape
Sequences (1 of 2)

• 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

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.10 Printing Literals and Escape
Sequences (2 of 2)
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.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11 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

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.1 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

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.2 scanf Conversion Specifiers (1 of 5)

• 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

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.2 scanf Conversion Specifiers (2 of 5)
Integers

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.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.2 scanf Conversion Specifiers (3 of 5)
Floating-point numbers

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.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.2 scanf Conversion Specifiers (4 of 5)
Characters and strings

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.

Scan set

Conversion specifier Description


[scan characters] Scan a string for a set of characters that are stored in an
array.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.2 scanf Conversion Specifiers (5 of 5)
Miscellaneous

Conversion specifier Description


p Read an address of the same form produced when an address
is output with %p in a printf statement.
n Store the number of characters input so far in this call to
scanf. The corresponding argument must be a pointer to an
int.
% Skip a percent sign (%) in the input.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.3 Reading Integers (1 of 3)
• Figure 9.12 reads integers with the various integer
conversion specifiers and displays the integers as
decimal numbers
• Conversion specification %i can input decimal, octal and
hexadecimal integers.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.3 Reading Integers (2 of 3)
1. // fig09_12.c
2. // Reading input with integer conversion specifiers
3. #include <stdio.h>
4.
5. int main(void) {
6. int a = 0;
7. int b = 0;
8. int c = 0;
9. int d = 0;
10. int e = 0;
11. int f = 0;
12. int g = 0;
13.
14. puts("Enter seven integers: ");
15. scanf("%d%i%i%i%o%u%x", &a, &b, &c, &d, &e, &f, &g);
16.
17. puts("\nThe input displayed as decimal integers is:");
18. printf("%d %d %d %d %d %d %d\n", a, b, c, d, e, f, g);
19. }
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
9.11.3 Reading Integers (3 of 3)
Output:

Enter seven integers:


-70 -70 070 0x70 70 70 70

The input displayed as decimal integers is:


-70 -70 56 112 56 70 112

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.4 Reading Floating-Point Numbers (1 of 3)

• When inputting floating-point numbers, any of the floating-


point conversion specifiers e, E, f, g or G can be used
• Figure 9.13 reads three floating-point numbers, one with
each of the three types of floating conversion specifiers,
and displays all three numbers with conversion specifier f

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.4 Reading Floating-Point Numbers (2 of 3)
1. // fig09_13.c
2. // Reading input with floating-point conversion specifiers
3. #include <stdio.h>
4.
5. int main(void) {
6. double a = 0.0;
7. double b = 0.0;
8. double c = 0.0;
9.
10. puts("Enter three floating-point numbers:");
11. scanf("%le%lf%lg", &a, &b, &c);
12.
13. puts("\nUser input displayed in plain floating-point
notation:");
14. printf("%f\n%f\n%f\n", a, b, c);
15. }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.4 Reading Floating-Point Numbers (3 of 3)

Output:
Enter three floating-point numbers:
1.27987 1.27987e+03 3.38476e-06

User input displayed in plain floating-point


notation:
1.279870
1279.870000
0.000003

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.5 Reading Characters and Strings (1 of 2)

• Characters and strings are input with conversion


specifiers c and s
• Figure 9.14 prompts the user to enter a string
– Inputs the first character of the string with %c
– Inputs the remainder of the string with %s

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.5 Reading Characters and Strings (2 of 2)
1. // fig09_14.c
2. // Reading characters and strings
3. #include <stdio.h>
4.
5. int main(void) {
6. char x = '\0';
7. char y[9] = "";
8.
9. printf("%s", "Enter a string: ");
10. scanf("%c%8s", &x, y);
11.
12. printf("The input was '%c' and \"%s\"\n", x, y);
13. }

Output:
Enter a string: Sunday
The input was

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.6 Using Scan Sets (1 of 4)
• A sequence of characters can be input using a scan set—a
set of characters enclosed in square brackets, [], and
preceded by %
• Scans the characters in the input stream, looking only for
those characters that match ones in the scan set
• Each time a character is matched, it’s stored in the scan set’s
corresponding character array argument
• Stops inputting characters when scanf encounters a
character not contained in the scan set
• Figure 9.15 uses the scan set [aeiou] to scan the input
stream for vowels
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
9.11.6 Using Scan Sets (2 of 4)
1. // fig09_15.c
2. // Using a scan set
3. #include <stdio.h>
4.
5. int main(void) {
6. char z[9] = "";
7.
8. printf("%s", "Enter string: ");
9. scanf("%8[aeiou]", z); // search for set of characters
10.
11. printf("The input was \"%s\"\n", z);
12. }

Output:
Enter string: ooeeooahah
The input was "ooeeooa"

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.6 Using Scan Sets (3 of 4)
• An inverted scan set can scan for characters not
contained in the scan set
• Place a caret (^) in the square brackets before the scan
characters
• When a character contained in the inverted scan set is
encountered, input terminates
• Figure 9.16 uses the inverted scan set [^aeiou] to
search for “non-vowels”

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.6 Using Scan Sets (4 of 4)
1. // fig09_16.c
2. // Using an inverted scan set
3. #include <stdio.h>
4.
5. int main(void) {
6. char z[9] = "";
7.
8. printf("%s", "Enter a string: ");
9. scanf("%8[^aeiou]", z); // inverted scan set
10.
11. printf("The input was \"%s\"\n", z);
12.}
Output:
Enter a string: String
The input was "Str"
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
9.11.7 Using Field Widths (1 of 2)
• A field width can be used in a scanf conversion specifier
to read a specific number of characters from the input
stream
• Figure 9.17 inputs a series of consecutive digits as a two-
digit integer and an integer consisting of the remaining
digits in the input stream

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.7 Using Field Widths (2 of 2)
1. // fig09_17.c
2. // Inputting data with a field width
3. #include <stdio.h>
4.
5. int main(void) {
6. int x = 0;
7. int y = 0;
8.
9. printf("%s", "Enter a six digit integer: ");
10. scanf("%2d%d", &x, &y);
11.
12. printf("The integers input were %d and %d\n", x, y);
13.}
Output:
Enter a six digit integer: 123456
The integers input were 12 and 3456
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
9.11.8 Skipping Characters in an Input
Stream (1 of 3)
• Whitespace characters, such as space, newline and tab, at the
beginning of a format control string skip all leading whitespace
• Other literal characters ignore those characters at specific positions
in the input
• To eliminate unnecessary characters, include them in scanf’s
format control string
• The assignment suppression character * enables scanf to read
and discard data from the input without assigning it to a variable
• Figure 9.18 uses the assignment suppression character in the %c
conversion specification to indicate that a character appearing in the
input stream should be read and discarded

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.8 Skipping Characters in an Input
Stream (2 of 3)
1. // fig09_18.c
2. // Reading and discarding characters from the input stream
3. #include <stdio.h>
4.
5. int main(void) {
6. int month = 0;
7. int day = 0;
8. int year = 0;
9. printf("%s", "Enter a date in the form mm-dd-yyyy: ");
10. scanf("%d%*c%d%*c%d", &month, &day, &year);
11. printf("month = %d day = %d year = %d\n\n", month, day,
year);
12.
13. printf("%s", "Enter a date in the form mm/dd/yyyy: ");
14. scanf("%d%*c%d%*c%d", &month, &day, &year);
15. printf("month = %d day = %d year = %d\n", month, day,
year);
16. }

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


9.11.8 Skipping Characters in an Input
Stream (3 of 3)
Output:

Enter a date in the form mm-dd-yyyy: 07-04-2021


month = 7 day = 4 year = 2021

Enter a date in the form mm/dd/yyyy: 01/01/2021


month = 1 day = 1 year = 2021

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Copyright

This work is protected by United States copyright laws and is


provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved

You might also like