C Tutorial (18) : getch, putch, getchar & putchar

You can produce input and output in more ways than with the scanf() and printf() functions. This tutorial shows you some of C’s built-in I/O functions that you can use to control I/O. You can use these simple functions to build powerful data-entry routines of your own.

These functions offer the primitive capability to input and output one character at a time. Of course, you also can use the %c format specifier with scanf() and printf() for single characters; however, the character I/O functions explained here are a little easier to use, and they provide some capabilities that scanf() and printf() don’t offer.

putchar() and getchar()

getchar() gets a single character from the keyboard, and putchar() sends a single character to the screen. Figure shows you what happens when you use these functions. They work basically the way you think they do. You can use them just about anytime you want to print or input a single character into a variable.

c_putchar

Note : Always include the stdio.h header file when using this chapter’s I/O functions, just as you do for printf() and scanf().

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.

#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:

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

However, most C compilers warn you that this statement is rather useless.

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.

#include <stdio.h>
#include <string.h>

main()
{
int i;
char msg[25];

printf("Type up to 25 characters and then press Enter...\n"); 
for (i = 0; i < 25; i++) 
{ 
msg[i] = getchar(); //Outputs a single character 
 if (msg[i] == '\n')
 {
 i--;
  break;
 }
 } 

putchar('\n'); // One line break after the loop is done.
 for (; i >= 0; i--)
{
  putchar(msg[i]);
}
putchar('\n');
return(0);
}

Note : Notice that the second for loop variable i has no initial value. Actually, it does. i contains the last array subscript entered in the previous getchar() for loop. Therefore, the second for loop continues with the value of i left by the first for loop.

The getchar() input character typically is defined as an int, as done here. Integers and characters are about the only C data types you can use interchangeably without worry of typecasts. In some advanced applications, getchar() can return a value that won’t work in a char data type, so you’re safe if you use int.

The Newline Consideration

Although getchar() gets a single character, control isn’t returned to your program until the user presses Enter. The getchar() function actually instructs C to accept input into a buffer, which is a memory area reserved for input. The buffer isn’t released until the user presses Enter, and then the buffer’s contents are released a character at a time. This means two things:

One, the user can press the Backspace key to correct bad character input, as long as he or she hasn’t pressed Enter.

Two, the Enter keypress is left on the input buffer if you don’t get rid of it.

Getting rid of the Enter keypress is a problem that all beginning C programmers must face. Several solutions exist, but none is extremely elegant. Consider the following segment of a program:

printf("What are your two initials?\n"); 

firstInit = getchar();          // Input (G (CR) T (CR))

lastInit = getchar();

You would think that if the user typed GT, the G would go in the variable firstInit and the T would go in lastInit, but that’s not what happens. The first getchar() doesn’t finish until the user presses Enter because the G was going to the buffer. Only when the user presses Enter does the G leave the buffer and go to the program—but then the Enter is still on the buffer! Therefore, the second getchar() sends that Enter (actually, the \n that represents Enter) to lastInit. The T is still left for a subsequent getchar() (if there is one).

Tip : One way to fix this problem is to insert an extra getchar() that captures the Enter but doesn’t do anything with it.

Here is a workaround for the initial-getting problem:

printf("What are your two initials?\n"); 
firstInit = getchar();
n1 = getchar(); 
lastInit = getchar(); 
n1 = getchar();

This code requires that the user press Enter between each initial. You don’t have to do anything with the nl variable because nl exists only to hold the in-between newline. You don’t even have to save the newline keypress in a variable. The following code works just like the last:

printf("What are your two initials?\n"); 
firstInit = getchar();
getchar(); // Discards the newline 
lastInit = getchar();
getchar(); // Discards the newline

Some C compilers issue warning messages when you compile programs with a standalone getchar() on lines by themselves. As long as you use these getchar()s for discarding Enter keypresses, you can ignore the compiler warnings.

You also can request the two initials by requiring the Enter keypress after the user enters the two initials, like this:

printf("What are your two initials?\n"); 
firstInit = getchar();
lastInit = getchar(); 
getchar();

If the user types GP and then presses Enter, the G resides in the firstInit variable and the P resides in the lastInit variable.

A Little Faster: getch()

A character input function named getch() helps eliminate the leftover Enter keypress that getchar() leaves. getch() is unbuffered—that is, getch() gets whatever keypress the user types immediately and doesn’t wait for an Enter keypress. The drawback to getch() is that the user can’t press the Backspace key to correct bad input.The following code gets two characters without an Enter keypress following each one:

printf("What are your two initials?\n"); 
firstInit = getch();
lastInit = getch();

getch() is a little faster than getchar() because it doesn’t wait for an Enter keypress before grabbing the user’s keystrokes and continuing. Therefore, you don’t need a standalone getch() to get rid of the \n as you do with getchar().

Warning : getch() does not echo the input characters to the screen as getchar() does. Therefore, you must follow getch() with a mirror-image putch() if you want the user to see onscreen the character he or she typed. To echo the initials, you could do this:

printf("What are your two initials?\n"); 
firstInit = getch();
putch(firstInit);
lastInit = putch();
putch(lastInit);

Note : getch & putch are not standard functions (defined in conio.h), which may not be available on many platforms.

Switch & Case < Prev                                          Next > built-in functions for strings

Advertisements

3 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s