C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

The name getchar() sounds like “get character,” and putchar() sounds like “put character.”
Looks as though the designers of C knew what they were doing!


The following program prints C is fun, one character at a time, using putchar() to print each
element of the character array in sequence. Notice that strlen() is used to ensure that the for
doesn’t output past the end of the string.


Click here to view code image


// Example program #1 from Chapter 18 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter18ex1.c
/* This program is nothing more than a simple demonstration of the
putchar() function. */
// putchar() is defined in stdio.h, but string.h is needed for the
// strlen() function
#include <stdio.h>
#include <string.h>
main()
{
int i;
char msg[] = "C is fun";
for (i = 0; i < strlen(msg); i++)
{
putchar(msg[i]); //Outputs a single character
}
putchar('\n'); // One line break after the loop is done.
return(0);
}

The getchar() function returns the character input from the keyboard. Therefore, you usually
assign the character to a variable or do something else with it. You can put getchar() on a line by
itself, like this:


Click here to view code image


getchar(); /* Does nothing with the character you get */

However, most C compilers warn you that this statement is rather useless. The getchar() function
would get a character from the keyboard, but then nothing would be done with the character.


Here is a program that gets one character at a time from the keyboard and stores the collected
characters in a character array. A series of putchar() functions then prints the array backward.


Click here to view code image


// Example program #2 from Chapter 18 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter18ex2.c
/* This program is nothing more than a simple demonstration of the
getchar() function. */
Free download pdf