ungetc() in C/C++


The function ungetc() takes a character and pushes it back to the stream so that the character could be read again.

Here is the syntax of ungetc() in C language,

int ungetc(int character, FILE *stream)

Here,

character − The character to be pushed back to stream.

stream − The pointer to the file object.

Here is an example of ungetc() in C language,

Example

#include <stdio.h>
int main() {
   int c;
   while ((c = getchar()) != '0')
   putchar(c);
   ungetc(c, stdin);
   c = getchar();
   putchar(c);
   puts("");
   printf("The End!");
   return 0;
}

Output

s a b c t h 0
The End!

In the above program, a character of int type is declared. It will read the characters until 0/zero encounters. It will display characters and as zero encounters, it prints “The End!”.

int c;
while ((c = getchar()) != '0')
putchar(c);
ungetc(c, stdin)
c = getchar();
putchar(c);
puts("");
printf("The End!");

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements