Sams Teach Yourself C in 24 Hours (19 page)

BOOK: Sams Teach Yourself C in 24 Hours
13.35Mb size Format: txt, pdf, ePub
ads

E e 14

F f 15

Don’t panic when you see so many printf() function calls being used in Listing
ANALYSIS
5.5. In fact, the program in Listing 5.5 is very simple. The program has just one function body from lines 5–23.

The printf() function in line 6 prints out a headline that contains three fields: Hex(uppercase), Hex(lowercase), and Decimal.

Then, lines 7–22 print out the hex and decimal numbers 0 through 15. Sixteen printf()calls are made to accomplish the job. Each of the printf() calls has a format string as the first argument followed by three integers as three expressions. Note that the
5

hex format specifiers %X and %x are used within the format string in each of the printf() calls to convert the corresponding expressions to the hex format (both uppercase and lowercase).

In reality, nobody would write a program like the one in Listing 5.5. Instead, a loop can be used to call the printf() function repeatedly. Looping (or iteration) is introduced in Hour 7, “Working with Loops.”

Specifying the Minimum Field Width

The C language allows you to add an integer between the percent sign (%) and the letter in a format specifier. The integer is called the
minimum field width specifier
because it specifies the minimum field width and ensures that the output reaches the minimum width. For example, in %10f, 10 is a minimum field width specifier that ensures that the output is at least 10 character spaces wide. This is especially useful when printing out a column of numbers.

07 067231861x CH05 4.10.2000 11:00 AM Page 82

82

Hour 5

The example in Listing 5.6 shows how to use the minimum field width specifier.

TYPE

LISTING 5.6

Specifying the Minimum Field Width

1: /* 05L06.c: Specifying minimum field width */

2: #include

3:

4: main()

5: {

6: int num1, num2;

7:

8: num1 = 12;

9: num2 = 12345;

10: printf(“%d\n”, num1);

11: printf(“%d\n”, num2);

12: printf(“%5d\n”, num1);

13: printf(“%05d\n”, num1);

14: printf(“%2d\n”, num2);

15: return 0;

16: }

The following is the output I obtain by running the executable file 05L06.exe: 12

OUTPUT

12345

12

00012

12345

In Listing 5.6, two integer variables, num1 and num2, are declared in line 6, and
ANALYSIS
assigned 12 and 12345, respectively, in lines 8 and 9.

Without using any minimum field width specifiers, lines 10 and 11 print out the two integers by calling the printf() function. You can see in the output section that the output from the statement in line 10 is 12, which takes two character spaces, while the output 12345 from line 11 takes five character spaces.

In line 12, a minimum field width, 5, is specified by %5d. The output from line 12 therefore takes five character spaces, with three blank spaces plus two character spaces of 12.

(See the third output line in the output section.)

The %05d in printf(), shown in line 13, indicates that the minimum field width is 5, and the 0 indicates that zeros are used to fill, or “pad,” the spaces. Therefore, you see the output made by the execution of the statement in line 13 is 00012.

07 067231861x CH05 4.10.2000 11:00 AM Page 83

Handling Standard Input and Output

83

The %2d in line 14 sets the minimum field width to 2, but you still see the full-size output of 12345 from line 14. This means that when the minimum field width is shorter than the width of the output, the latter is taken, and the output is still printed in full.

Aligning Output

As you might have noticed in the previous section, all output is right-justified. In other words, by default, all output is placed on the right edge of the field, as long as the field width is longer than the width of the output.

You can change this and force output to be left-justified. To do so, you need to prefix the minimum field specifier with the minus sign (-). For example, %-12d specifies the minimum field width as 12, and justifies the output from the left edge of the field.

Listing 5.7 gives an example aligning output by left- or right-justification.

TYPE

LISTING 5.7

Left- or Right-Justified Output

1: /* 05L07.c: Aligning output */

2: #include

3:

4: main()

5: {

6: int num1, num2, num3, num4, num5;

7:

8: num1 = 1;

9: num2 = 12;

10: num3 = 123;

11: num4 = 1234;

5

12: num5 = 12345;

13: printf(“%8d %-8d\n”, num1, num1);

14: printf(“%8d %-8d\n”, num2, num2);

15: printf(“%8d %-8d\n”, num3, num3);

16: printf(“%8d %-8d\n”, num4, num4);

17: printf(“%8d %-8d\n”, num5, num5);

18: return 0;

19: }

I get the following output displayed on the screen of my computer after I run the executable 05L07.exe:

1 1

OUTPUT

12 12

123 123

1234 1234

12345 12345

07 067231861x CH05 4.10.2000 11:00 AM Page 84

84

Hour 5

In Listing 5.7, there are five integer variables, num1, num2, num3, num4, and num5,
ANALYSIS
that are declared in line 6 and are assigned values in lines 8–12.

These values represented by the five integer variables are then printed out by the printf() functions in lines 13–17. Note that all the printf() calls have the same first argument: “%8d %-8d\n”. Here the first format specifier, %8d, aligns the output at the right edge of the field, and the second specifier, %-8d, aligns the output to the left edge of the field.

After the execution of the statements in lines 13–17, the alignment is accomplished and the output is put on the screen like this:

1 1

12 12

123 123

1234 1234

12345 12345

Using the Precision Specifier

You can put a period . and an integer right after the minimum field width specifier. The combination of the period (.) and the integer makes up a
precision specifier
. You can use the precision specifier to determine the number of decimal places for floating-point numbers, or to specify the maximum field width (or length) for integers or strings. (Strings in C are introduced in Hour 13, “Manipulating Strings.”)

For instance, with %10.3f, the minimum field width length is specified as 10 characters long, and the number of decimal places is set to 3. (Remember, the default number of decimal places is 6.) For integers, %3.8d indicates that the minimum field width is 3, and the maximum field width is 8.

Listing 5.8 gives an example of using precision specifiers.

TYPE

LISTING 5.8

Using Precision Specifiers

1: /* 05L08.c: Using precision specifiers */

2: #include

3:

4: main()

5: {

6: int int_num;

7: double flt_num;

8:

9: int_num = 123;

10: flt_num = 123.456789;

11: printf(“Default integer format: %d\n”, int_num);

07 067231861x CH05 4.10.2000 11:00 AM Page 85

Handling Standard Input and Output

85

12: printf(“With precision specifier: %2.8d\n”, int_num);

13: printf(“Default float format: %f\n”, flt_num);

14: printf(“With precision specifier: %-10.2f\n”, flt_num);

15: return 0;

16: }

After running the executable file 05L08.exe on my computer, I get the following output on the screen:

Default integer format: 123

OUTPUT

With precision specifier: 00000123

Default float format: 123.456789

With precision specifier: 123.46

The program in Listing 5.8 declares one integer variable, int_num, in line 6, and
ANALYSIS
one floating-point number, flt_num, in line 7. Lines 9 and 10 assign 123 and 123.456789 to int_num and flt_num, respectively.

In line 11, the default integer format is specified for the integer variable, int_num, while the statement in line 12 specifies the integer format with a precision specifier that indicates that the maximum field width is eight characters long. Therefore, you see that five zeros are padded prior to the integer 123 in the second line of the output.

For the floating-point variable, flt_num, line 13 prints out the floating-point value in the default format, and line 14 reduces the decimal places to two by putting the precision specifier .2 within the format specifier %-10.2f. Note here that left-justification is also specified by the minus sign (-) in the floating-point format specifier.

The floating-point number 123.46 in the fourth line of the output is produced by the
5

statement in line 14 with the precision specifier for two decimal places. Therefore, 123.456789 rounded to two decimal places becomes 123.46.

Summary

In this lesson you’ve learned the following important concepts, specifiers, and functions:

• The C language treats a file as a series of bytes.

• stdin, stdout, and stderr are three file streams that are pre-opened and always available for you to use.

• The C library functions getc() and getchar() can be used to read in one character from the standard input.

• The C library functions putc() and putchar() can be used to write one character to the standard output.

07 067231861x CH05 4.10.2000 11:00 AM Page 86

86

Hour 5

• %x or %X can be used to convert decimal numbers to hex numbers.

• A minimum field width can be specified and ensured by adding an integer into a format specifier.

• An output can be aligned at either the left or right edge of the output field.

• A precision specifier can be used to specify the decimal place number for floating-point numbers, or the maximum field width for integers or strings.

In next lesson you’ll learn about some important operators in C.

Q&A

Q What are
stdin
,
stdout
, and
stderr
?

A
In C, a file is treated as a series of bytes that is called file stream. stdin, stdout, and stderr are all pre-opened file streams. stdin is the standard input for reading; stdout is the standard output for writing; stderr is the standard error for outputting error messages.

Q How much is the hex number 32?

A
Hexadecimal, or hex for short, is a base-16 numerical system. Therefore, 32 (hex) is equal to 3*161+2*160, or 50 in decimal.

Q Are
getc(stdin)
and
getchar()
equivalent?

A
Because the getchar() function reads from the file stream stdin by default, getc(stdin) and getchar() are equivalent in this case.

Q In the function
printf(“The integer %d is the same as the hex %x”, 12, 12)
, what is the relation between the format specifiers and the expressions?

A
The two format specifiers, %d and %x, specify the formats of numeric values contained in the expression section. Here the first numeric value of 12 is going to be printed out in integer format, while the second 12 (in the expression section) will be displayed in the hex format. Generally speaking, the number of format specifiers in the format section should match the number of expressions in the expression section.

Workshop

To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix D, “Answers to Quiz Questions and Exercises.”

07 067231861x CH05 4.10.2000 11:00 AM Page 87

Handling Standard Input and Output

87

Quiz

1. Can you align your output at the left edge, rather than the right edge, of the output field?

2. What is the difference between putc() and putchar()?

3. What does getchar() return?

4. Within %10.3f, which part is the minimum field width specifier, and which one is the precision specifier?

Exercises

1. Write a program to put the characters B, y, and e together on the screen.

2. Display the two numbers 123 and 123.456 and align them at the left edge of the field.

3. Given three integers, 15, 150, and 1500, write a program that prints the integers on the screen in the hex format.

4. Write a program that uses getchar() and putchar() to read in a character entered by the user and write the character to the screen.

5. If you compile the following C program, what warning or error messages will you get?

main()

{

int ch;

ch = getchar();

putchar(ch);

5

return 0;

}

07 067231861x CH05 4.10.2000 11:00 AM Page 88

BOOK: Sams Teach Yourself C in 24 Hours
13.35Mb size Format: txt, pdf, ePub
ads

Other books

Tube Riders, The by Ward, Chris
Beloved Forever by Kit Tunstall
Vanished by Kat Richardson
Listen to the Moon by Rose Lerner
Dead City by Lee J Isserow
Dissonance by Erica O'Rourke
Los asesinatos e Manhattan by Lincoln Child Douglas Preston


readsbookonline.com Copyright 2016 - 2024