21
This presentation includes custom animations. To view the animations, you must view the presentation in Slide Show mode and activeX controls must be allowed. If you have opened this lesson in PowerPoint, use the PowerPoint menus to view it in slide show mode. If you have opened this lesson in a browser and see a bar similar to that below, click on the Slide Show icon A notice similar to the one below may appear warning that ActiveX or other scripts are disabled. Enable the controls for this website in order to see the animations.

miniLesson on the printf() function

Embed Size (px)

Citation preview

Page 1: miniLesson on the printf() function

This presentation includes custom animations.

To view the animations, you must view the presentation in Slide Show modeand activeX controls must be allowed.

If you have opened this lesson in PowerPoint, use the PowerPoint menus to view it in slide show mode.

If you have opened this lesson in a browser and see a bar similar to that below, click on the Slide Show icon

A notice similar to the one below may appear warning that ActiveX or other scripts are disabled. Enable the controls for this website in order to see the animations.

Page 2: miniLesson on the printf() function

printf

Christine S. WolfeOhio University Lancaster2008-Aug-01

This lesson describes the syntax and use of the printf library functions:printf()fprintf()sprintf()

Vocabulary:

To use printf, fprintf, or sprintf, you must #include <stdio.h>ClickTip

ASCIIconversion specifier file name extensionFILE pointerflagfprintf()placeholderprecision

printf()resultsprintf()stdouttext fileunicodewidth

Page 3: miniLesson on the printf() function

3Christine S. WolfeOhio University Lancaster2008-Aug-01

The printf functions are used to produce formatted output.

printf sends the output to stdout.stdout is a predefined macro that represents the standard output and is typically the computer monitor although this can be changed by the end user.

ClickTip

ClickTip

A text file is one in which every byte is a character from the ASCII, Unicode, or other character set. The extension can be anything the programmer chooses.

sprintf sends the output to a string variable.

ClickTip

fprintf sends the output to a text file.

/* VARIABLE DECLARATIONS */char Message[81];

The target string must be long enough to hold the entire output + 1 byte for the null.

Page 4: miniLesson on the printf() function

4Christine S. WolfeOhio University Lancaster2008-Aug-01

syntax diagrams for the printf cousins from Appendix B of the text

All 3 include, for each placeholder, an argument that specifies the value to be used in place of the placeholder.

All 3 include an output string that specifies what to output expressed as: literals + escape sequences + placeholders.

All 3 return the number of bytes (characters) written to output.

Although the square brackets indicate that the arguments at the end are optional, that is a bit misleading. They are required if there are any placeholders in the output string. There must be one argument (value) provided for each placeholder.

ClickTip

int printf (const char *format [, argument, …]);

int fprintf (FILE *stream, const char *format [, argument, …]);

int sprintf (char *buffer, const char *format [, argument, …]);

Page 5: miniLesson on the printf() function

5Christine S. WolfeOhio University Lancaster2008-Aug-01

The syntax of the cousins varies only in the required arguments.

sprintf has 2 required arguments. The first argument in sprintf identifies the destination string variable and the 2nd argument is the output string.

fprintf has 2 required arguments. The first argument in fprintf identifies the file pointer for the destination file and the 2nd argument is the output string.

printf has 1 required argument. That required argument is the output string.

stdout is treated like a file pointer in C so the following 2 constructions produce the same result: printf("Hello"); fprintf(stdout, "Hello");

ClickTip

int printf (const char *format [, argument, …]);

int fprintf (FILE *stream, const char *format [, argument, …]);

int sprintf (char *buffer, const char *format [, argument, …]);

Page 6: miniLesson on the printf() function

6

int printf (const char *format [, argument, …]);

All 3 of the printf functions return a result with a data type of int.

The result is a count of the number of characters in the output.

Example:

NumLetters = printf(“Hello”);

NumLetters == 5

Christine S. WolfeOhio University Lancaster2008-Aug-01

Page 7: miniLesson on the printf() function

7

It is not necessary to assign the result to a value – but if the result is assigned, then the variable on the left of the assignment operator MUST be an int.

Example:

int NumLetters;

printf(“Goodbye”);

NumLetters = printf(“Hello”);

If assigned, the result must be stored in an int

It is OK to call a function without

assigning its value to a variable.

Christine S. WolfeOhio University Lancaster2008-Aug-01

Page 8: miniLesson on the printf() function

8

int printf (const char *format [, argument, …]);

const char *format means that you must include an output string that is a set of characters that are to be displayed on the screen along with escape sequences and conversion specifiers (placeholders).

Christine S. WolfeOhio University Lancaster2008-Aug-01

printf("First name: ");

printf("Thank you. Please visit again.");

printf("Please enter a number"); Please enter a number

First name:

Thank you. Please visit again.

printf("Report Menu"); Report Menu

What is the result of each of the following statements? (Click each button to check your answer.)

Page 9: miniLesson on the printf() function

9Christine S. WolfeOhio University Lancaster2008-Aug-01

Escape sequences are used to express output that cannot be represented on the keyboard or to express output that might be mistaken for C code.

Examples of output that cannot be represented on the keyboard:

\r Carriage Return (move cursor to beginning of current line)\f Form Feed (new page)\a Audible Alert (bell)

Examples of output that might be mistaken for C code.

\n Newline \t Horizontal Tab \v Vertical Tab \b Backspace \\ Backslash \? Question mark \' Single quote \" Double quote %% Percent sign (honorary escape sequence)

int printf (const char *format [, argument, …]);

Page 10: miniLesson on the printf() function

10

What is the result of each of the following statements? (Click each button to check your answer.)

printf("a\\c\\d");

printf("abc");

printf("a\tb\tc");

printf("a\c\d");

printf("a"b");

printf("a\"b");

printf("a\nb\nc");

abc

a b c

a b c

syntax error!!!

a"b

a\c\d

acd

printf("a\nb\tc");a b c

\c and \d are not defined escape sequences so the \ is ignored.

Christine S. WolfeOhio University Lancaster2008-Aug-01

printf("a%%c\\d"); a%c\d

Page 11: miniLesson on the printf() function

11

int printf (const char *format [, argument, …]);

Conversion specifiers are placeholders for values are not known at the time the code is written.

Some common conversion specifiers:

for data type use placeholderint %dfloat %fchar %cstring %sint (base 10) %i

Christine S. WolfeOhio University Lancaster2008-Aug-01

http://www.cplusplus.com/reference/clibrary/cstdio/printf.htmlSee the full list of conversion specifiers at:

type%

Page 12: miniLesson on the printf() function

12

printf(“The answer is %d”, 3);

printf(“She is %d years old.”, age);

printf(“%d + %d = %d”, numA, numB, numA + numB);

Christine S. WolfeOhio University Lancaster2008-Aug-01

For each placeholder, there must be a value in the argument list.

The data type of the value must match or be cast as the value indicated by the format specifier.

The order in which the placeholders appear in the output string must exactly match the order of the values in the argument list.

1 placeholder 1 value

1 placeholder 1 value

3 placeholder 3 values

Page 13: miniLesson on the printf() function

13

Assume the following code appears before the statements below:int answer;int age;int numA;int numB;answer = 3;age = 22;numA = 14;numB = 12;

Christine S. WolfeOhio University Lancaster2008-Aug-01

printf("%d + %d = %d", numA, numB, numA + numB);

printf("She is %d years old.", age);

printf(“The answer is %d”, 3); The answer is 3

14 + 12 = 26

She is 22 years old.

What is the result of each of the following statements? (Click each button to check your answer.)

printf("%d + %d = %d", numA, numB, numA + numA); 14 + 12 = 28

Understand why the computer displays a falsehood.

Page 14: miniLesson on the printf() function

14

Assume the following code appears before the statements below:

double classAvg = 78.5;char AvgLetter = 'B';

Christine S. WolfeOhio University Lancaster2008-Aug-01

printf(“pi can be expressed as %c, %d, or %f”, PI, 3, 22/7.0);

printf(“The average letter grade was %c”, AvgLetter);

printf(“The class average was %f”, classAvg);

The class average was 78.500000

pi can be expressed as π, 3, or 3.142857

The average letter grade was B

What is the result of each of the following statements? (Click each button to check your answer.)

PI is a predefined keyword in C.ClickTip

Page 15: miniLesson on the printf() function

15

Notice that the arguments can be literals, variables, or any expression that returns a value with the appropriate data type.

printf(“%d %d %d”, 5, NumClients, 6 + 3);

literal variable expression

Christine S. WolfeOhio University Lancaster2008-Aug-01

Page 16: miniLesson on the printf() function

16

As in all C code – you must sweat the details!

Sweat it that there is a comma between every pair of arguments - including the output string if it is followed by another argument.

Christine S. WolfeOhio University Lancaster2008-Aug-01

Sweat it that the closing double quote is after the output string - NOT after the last argument!

Sweat it that there is a semicolon at the end of the statement.

printf(“pi can be expressed as %c, %d, or %f” , PI, 3, 22/7.0);

printf("Hello World");

printf(“The average letter grade was %c”, AvgLetter);

Page 17: miniLesson on the printf() function

17

Sweat it that printf does not automatically add spaces around the inserted arguments. The programmer must include the spaces in the output string.

Christine S. WolfeOhio University Lancaster2008-Aug-01

printf("She is%dyears old.", 23); She is23years old.

printf("She is %d years old.", 23); She is 23 years old.

Page 18: miniLesson on the printf() function

18

Sweat it that the programmer must code every character that should appear on the screen,

… to get commas in a list of values, include the commas at the appropriate place inside the format string

Christine S. WolfeOhio University Lancaster2008-Aug-01

printf(“%d %d %d”, 5, NumClients, 6 + 3); 5 123 9

printf(“%d, %d, %d”, 5, NumClients, 6 + 3); 5, 123, 9

The DOS window uses a non-proportional font. Each character uses the exact same amount of horizontal space. Courier New is an example of a non-proportional font.

ClickTip

Page 19: miniLesson on the printf() function

19

The printf placeholders may include formatting options.

Required

type%

Optional

Christine S. WolfeOhio University Lancaster2008-Aug-01

[flags] [width] [.prec] [hlL] type%

Page 20: miniLesson on the printf() function

20http://www.cplusplus.com/reference/clibrary/cstdio/printf.html

In your textbook, see Table 12.2 "Placeholders for printf format strings"

The following link is also very helpful.Christine S. WolfeOhio University Lancaster2008-Aug-01

[flags] [width] [.prec] [hlL]% type

[flags] The most common flag is the minus sign, -. It reverses the normal left/right alignment. Normal for text is left aligned, normal for numeric data is right aligned.

[width] The width specifies the MINIMUM number of characters to be displayed. If the value requires fewer characters, the width is padded with blank spaces. If the value requires more characters, all the characters are output using a greater width. The specified width is a MINIMUM.For numeric types, the width specifer includes space for the digits (both right and left of the decimal point) and the decimal point itself.

[.prec] The precision option specifies the exact number of digits to display to the right of the decimal point. These digits count as part of the width.

[hlL] Also referred to as the length option, this indicates a modification of the data type as short or long.

Page 21: miniLesson on the printf() function

21Christine S. WolfeOhio University Lancaster2008-Aug-01

printf(“Average cost: %-8.3f !” , 3.4);

printf(“ ***%-10.4f***”, 12.333);

printf(“ ***%10.1f***”, 12.333); *** 12.3***

Average cost: 3.400 !

***12.3330 ***

printf(“%5s%10s\n”, "ID","Amount");printf(“\n%5d%10.2f”, 1,12.15);printf(“\n%5d%10.2f”, 2,1.6);printf(“\n%5d%10.2f”, 3,4500.5);printf(“\n%5d%10.2f”, 4,1234567890.0123);printf(“\n%5d%10.2f”, 5,16.367);

ID Amount

1 12.15 2 1.60 3 4500.50 41234567890.01 5 16.37

What is the result of each of the following statements? (Click each button to check your answer.)

Make sure you understand why the row for ID 4 is out of line with the others.Send me an email telling me how you would correct the problem.