ungetc() in C/C++

CC++Server Side Programming

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!");
raja
Published on 05-Nov-2018 12:03:28
Advertisements