Sams Teach Yourself C in 21 Days

(singke) #1
Working with the Screen, Printer, and Keyboard 347

14


“Ungetting” a Character with ungetc()
What does ungettinga character mean? An example should help you understand.
Suppose that your program is reading characters from an input stream and can detect the
end of input only by reading one character too many. For example, you might be
inputting digits only, so you know that input has ended when the first nondigit character
is encountered. That first nondigit character might be an important part of subsequent
data, but it has been removed from the input stream. Is it lost? No, it can be “ungotten”
or returned to the input stream, where it is then the first character read by the next input
operation on that stream.
To “unget” a character, you use the ungetc()library function. Its prototype is
int ungetc(int ch, FILE *fp);
The argument chis the character to be returned. The argument *fpspecifies the stream
that the character is to be returned to, which can be any input stream. For now, simply
specifystdinas the second argument:ungetc(ch, stdin);. The notation FILE *fpis
used with streams associated with disk files; you’ll learn about this on Day 16.
You can unget only a single character to a stream between reads, and you can’t unget EOF
at any time. The function ungetc()returnschon success and EOFif the character can’t
be returned to the stream.

Line Input
The line-input functions read a line from an input stream—they read all characters up to
the next newline character. The standard library has two line input functions,gets()and
fgets().

Thegets()Function
You were introduced to the gets()function on Day 10, “Working with Characters and
Strings.” This is a straightforward function, reading a line from stdinand storing it in a
string. The function prototype is
char *gets(char *str);

DOunderstand the difference between
echoed and nonechoed input.
DOunderstand the difference between
buffered and unbuffered input.

DON’Tuse non-ANSI standard functions
if portability is a concern.
DON’Texpect non-ANSI standard func-
tions to work the same if you switch
compilers.

DO DON’T


22 448201x-CH14 8/13/02 11:12 AM Page 347

Free download pdf