Sams Teach Yourself C in 24 Hours (18 page)

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

2: #include

3:

4: main()

5: {

6: int ch1, ch2;

7:

07 067231861x CH05 4.10.2000 11:00 AM Page 75

Handling Standard Input and Output

75

8: printf(“Please type in two characters together:\n”);

9: ch1 = getc( stdin );

10: ch2 = getchar( );

11: printf(“The first character you just entered is: %c\n”, ch1);

12: printf(“The second character you just entered is: %c\n”, ch2);

13: return 0;

14: }

After running the executable file, 05L02.exe, and entering two characters (H and i) together without spaces, I press the Enter key and have the following output displayed on the screen of my computer:

Please type in two character together:

OUTPUT

Hi

The first character you just entered is: H

The second character you just entered is: i

The program in Listing 5.2 is quite similar to the one in Listing 5.1, except that
ANALYSIS
this one reads in two characters.

The statement in line 6 declares two integers, ch1 and ch2. Line 8 displays a message asking the user to enter two characters together.

Then, the getc() and getchar() functions are called in lines 9 and 10, respectively, to read in two characters entered by the user. Note that in line 10, nothing is passed to the getchar() function. This is because, as mentioned earlier, getchar() uses the default input file stream—stdin. You can replace the getchar() function in line 10 with getc(stdin) because getc(stdin) is equivalent to getchar().

5

Lines 11 and 12 send two characters (kept by ch1 and ch2, respectively) to the screen.

Printing Output on the Screen

Besides getc() and getchar() for reading, the C language also provides two functions, putc() and putchar(), for writing. The following two sections introduce these functions.

Using the
putc()
Function

The putc() function writes a character to the specified file stream, which, in your case, is the standard output pointing to your screen.

07 067231861x CH05 4.10.2000 11:00 AM Page 76

76

Hour 5

Syntax Entry

AX

The syntax for the putc() function is

#include

YNT

int putc(int c, FILE *stream);

S

Here the first argument, int c, indicates that the output is a character saved in an integer variable c; the second argument, FILE *stream, specifies a file stream. If successful, putc() returns the character written; otherwise, it returns EOF.

In this lesson the standard output stdout is specified as the output file stream in putc().

The putc() function is used in Listing 5.3 to put the character A on the screen.

TYPE

LISTING 5.3

Putting a Character on the Screen

1: /* 05L03.c: Outputting a character with putc() */

2: #include

3:

4: main()

5: {

6: int ch;

7:

8: ch = 65; /* the numeric value of A */

9: printf(“The character that has numeric value of 65 is:\n”);

10: putc(ch, stdout);

11: return 0;

12: }

The following output is what I get from my machine:

The character that has numeric value of 65 is:

OUTPUT
A

As mentioned, the header file stdio.h, containing the declaration of putc(), is
ANALYSIS
included in line 2.

The integer variable, ch, declared in line 6, is assigned the numeric value of 65 in line 8.

The numeric value of character A is 65 in the ASCII character set.

Line 9 displays a message to remind the user of the numeric value of the character that is going to be put on the screen. Then, the putc() function in line 10 puts character A on the screen. Note that the first argument to the putc() function is the integer variable (ch) that contains 65, and the second argument is the standard output file stream, stdout.

07 067231861x CH05 4.10.2000 11:00 AM Page 77

Handling Standard Input and Output

77

Another Function for Writing:
putchar()

Like putc(), putchar() can also be used to put a character on the screen. The only difference between the two functions is that putchar() needs only one argument to contain the character. You don’t need to specify the file stream because the standard output (stdout) is set as the file stream to putchar().

Syntax Entry

AX

The syntax for the putchar() function is

#include

YNT

int putchar(int c);

S

Here int c is the argument that contains the numeric value of a character. The function returns EOF if an error occurs; otherwise, it returns the character that has been written.

An example of using putchar() is demonstrated in Listing 5.4.

TYPE

LISTING 5.4

Outputting Characters with putchar().

1: /* 05L04.c: Outputting characters with putchar() */

2: #include

3:

4: main()

5: {

6: putchar(65);

7: putchar(10);

8: putchar(66);

9: putchar(10);

10: putchar(67);

5

11: putchar(10);

12: return 0;

13: }

After running the executable file, 05L04.exe, I get the following output: A

OUTPUT
B

The way to write the program in Listing 5.4 is a little bit different. There is no
ANALYSIS
variable declared in the program. Rather, integers are passed to putchar() directly, as shown in lines 6–11.

As you might have figured out, 65, 66, and 67 are, respectively, the numeric values of characters A, B, and C in the ASCII character set. From exercise 5 of Hour 4,

“Understanding Data Types and Keywords,” you can find out that 10 is the numeric value of the newline character (\n).

07 067231861x CH05 4.10.2000 11:00 AM Page 78

78

Hour 5

Therefore, respectively, lines 6 and 7 put character A on the screen and cause the computer to start at the beginning of the next line. Likewise, line 8 puts B on the screen, and line 9 starts a new line. Then, line 10 puts C on the screen, and line 11 starts another new line. Accordingly, A, B, and C, are put at the beginning of three consecutive lines, as shown in the output section.

Revisiting the
printf()
Function

The printf() function is the first C library function you used in this book to print out messages on the screen. printf() is a very important function in C, so it’s worth it to spend more time on it.

Syntax Entry

AX

The syntax for the printf() function is

#include

YNT

int printf(const char *format-string, . . .);

S

Here const char *format-string is the first argument that contains the format specifier(s); ... indicates the expression section that contains the expression(s) to be formatted according to the format specifiers. The number of expressions is determined by the number of the format specifiers inside the first argument. The function returns the number of expressions formatted if it succeeds. It returns a negative value if an error occurs.

const char * is explained later in this book. For the time being, consider the first argument to the printf() function as a string (a series of characters surrounded with double quotes) with some format specifiers inside. For instance, you can pass “The sum of two integers %d + %d is: %d.\n” to the function as the first argument.

Figure 5.1 shows the relationship between the format string and expressions. Note that the format specifiers and the expressions are matched in order from left to right.

FIGURE 5.1

The relation between

Format

string

Expressions

the format string and

the expressions in

printf()
.

printf(“A floating-point: %f; An integer: %d.”, 123.45, 12345);
07 067231861x CH05 4.10.2000 11:00 AM Page 79

Handling Standard Input and Output

79

Please remember that you should use exactly the same number of expressions as the number of format specifiers within the format string.

The following are all the format specifiers that can be used in printf():

%c

The character format specifier.

%d

The integer format specifier.

%i

The integer format specifier (same as %d).

%f

The floating-point format specifier.

%e

The scientific notation format specifier (note the lowercase e).

%E

The scientific notation format specifier (note the uppercase E).

%g

Uses %f or %e, whichever result is shorter.

%G

Uses %f or %E, whichever result is shorter.

%o

The unsigned octal format specifier.

%s

The string format specifier.

%u

The unsigned integer format specifier.

%x

The unsigned hexadecimal format specifier (note the lowercase x).

%X

The unsigned hexadecimal format specifier (note the uppercase X).

%p

Displays the corresponding argument that is a pointer.

5

%n

Records the number of characters written so far.

%%

Outputs a percent sign (%).

Among the format specifiers in this list, %c, %d, %f, %e, and %E have been introduced so far. Several others are explained later in this book. The next section shows you how to convert decimal numbers to hexadecimal numbers by using %x or %X.

Converting to Hex Numbers

Since all data in a computer consists of binary data (a series of zeroes and ones), any data we work with or print out is really just some kind of human-readable representation of the binary data. As a programmer, it is often necessary to deal with binary data directly, but it is extremely time consuming to decipher a string of zeroes and ones and try to convert them to meaningful numeric or character data.

07 067231861x CH05 4.10.2000 11:00 AM Page 80

80

Hour 5

The solution to this problem is
hexadecimal notation
(or hex), which is a kind of shorthand to represent binary numbers. Hex is a compromise between the computer-readable base-2 (or binary) number system, and our more familiar base-10 (or decimal) system.

Converting numbers from hex to decimal (or from binary to hex) and back is far easier (not to mention quicker) than converting directly from binary to decimal or vice-versa.

The difference between a decimal number and a hexadecimal number is that the hexadecimal is a base-16 numbering system. A hexadecimal number can be represented by four bits. (24] is equal to 16, which means four bits can produce 16 unique numbers.) The hexadecimal numbers 0 through 9 use the same numeric symbols found in the decimal numbers 0 through 9. A, B, C, D, E, and F are used to represent, respectively, the numbers 10 through 15 in uppercase. (Similarly, in lowercase, a, b, c, d, e, and f are used to represent these hex numbers. Uppercase and lowercase hex are interchangeable and really just a matter of style.)

Listing 5.5 provides an example of converting decimal numbers to hex numbers by using

%x or %X in the printf() function.

TYPE

LISTING 5.5

Converting to Hex Numbers

1: /* 05L05.c: Converting to hex numbers */

2: #include

3:

4: main()

5: {

6: printf(“Hex(uppercase) Hex(lowercase) Decimal\n”);

7: printf(“%X %x %d\n”, 0, 0, 0);

8: printf(“%X %x %d\n”, 1, 1, 1);

9: printf(“%X %x %d\n”, 2, 2, 2);

10: printf(“%X %x %d\n”, 3, 3, 3);

11: printf(“%X %x %d\n”, 4, 4, 4);

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

13: printf(“%X %x %d\n”, 6, 6, 6);

14: printf(“%X %x %d\n”, 7, 7, 7);

15: printf(“%X %x %d\n”, 8, 8, 8);

16: printf(“%X %x %d\n”, 9, 9, 9);

17: printf(“%X %x %d\n”, 10, 10, 10);

18: printf(“%X %x %d\n”, 11, 11, 11);

19: printf(“%X %x %d\n”, 12, 12, 12);

20: printf(“%X %x %d\n”, 13, 13, 13);

21: printf(“%X %x %d\n”, 14, 14, 14);

22: printf(“%X %x %d\n”, 15, 15, 15);

23: return 0;

24: }

07 067231861x CH05 4.10.2000 11:00 AM Page 81

Handling Standard Input and Output

81

The following output is obtained by running the executable file, 05L05.exe, on my computer:

Hex(uppercase) Hex(lowercase) Decimal

OUTPUT

0 0 0

1 1 1

2 2 2

3 3 3

4 4 4

5 5 5

6 6 6

7 7 7

8 8 8

9 9 9

A a 10

B b 11

C c 12

D d 13

Other books

The Quartered Sea by Tanya Huff
Eye of the Storm by Ann Jacobs
The Widower's Two-Step by Rick Riordan
Alma Mater by Rita Mae Brown
Moon Flower by James P. Hogan
Too Many Cooks by Dana Bate
Without Consent by Frances Fyfield
Don't Let Go by Nona Raines
Miss Foster’s Folly by Alice Gaines