Format
#include <stdio.h> int ungetc(int c, FILE *stream);
Language Level: ANSI, POSIX, XPG4
ungetc pushes the unsigned character c back onto the
given input stream. However, only one sequential
character or consecutive character is guaranteed to be pushed
back onto the input stream if you call ungetc consecutively. The stream
must be open for reading. A subsequent read operation on the stream
starts with c. The character c cannot be
the EOF character.
Characters placed on the stream by ungetc will be erased if fseek, fsetpos, rewind, or fflush is called before the character is read from the stream.
Return Value
ungetc returns the integer argument c
converted to an unsigned char, or EOF if c cannot be
pushed back.
Example
In this example, the while statement reads decimal
digits from an input data stream by using arithmetic statements
to compose the numeric values of the numbers as it reads them.
When a nondigit character appears before the end of the file,
ungetc replaces it in the input stream so that later input
functions can process it.
#include <stdio.h> #include <ctype.h>
int main(void)
{
FILE *stream;
int ch;
unsigned int result = 0;
while ((ch = getc(stdin)) != EOF && isdigit(ch))
result = result * 10 + ch - '0';
if (ch != EOF)
ungetc(ch,stdin);
/* Put the nondigit character back */
printf("Input number : %d\n", result);
return 0;
/************************************************
For the following input:
12345s
The output should be:
Input number : 12345 ************************************************/ }
![]()
getc - getchar -- Read a Character
fflush -- Write Buffer to File
fseek -- Reposition File Position
fsetpos -- Set File Position
putc - putchar -- Write a Character
rewind -- Adjust Current File Position
_ungetch -- Push Character Back to
Keyboard
<stdio.h>