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 the default file stream to putchar().
The syntax for the putchar() function is
#include <stdio.h>
int putchar(int c);
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 <stdio.h>
3:
4: main()
5: {
6: putchar(65);
7: putchar(10);
8: putchar(66);
9: putchar(10);
10: putchar(67);
11: putchar(10);
12: return 0;
13: }
OUTPUT
After running the executable file, 05L04.exe, I get the following output:
C:\app> 05L04
A
B
C
C:\app>
ANALYSIS
The way to write the program in Listing 5.4 is a little bit different. There is no 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. From exercise 5 of Hour 4, "Data Types and Names in C," or from Appendix C, "ASCII Character Set," you can find out that 10 is the numeric value of the newline character (\n).
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 beginnings of three consecutive lines, as shown in the output section.
- 6 views