Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use ungetc() in C++

Sarah Tanveer

The ungetc() function is a built-in function defined in the <cstdio> header that pushes the last read character back into the input stream as if undoing a getc() function. There are no changes made to the content of the file.

Successful executions of file positioning functions (such as fseek(), fsetpos(), and rewind()) will disregard characters pushed into the stream.


int ungetc(int char, FILE* stream)


  1. char: the int promotion (i.e., the character will be internally converted to an unsigned char) of the character to be pushed back into the stream.

  2. stream: pointer to the file stream that char is pushed into. This could be standard input, standard output, any file stream, etc.

    • If binary stream, the stream position indicator is decremented by 1.

    • If text stream, the stream position indicator is undefined. When all the characters that were pushed back are read, the value of the stream position indicator takes the same value as before ungetc() was called.

Return value

If successful, the function will return char and a clear EOF (end of file) indicator. Else, EOF is returned with no changes made to the stream.

Example code

This code extracts digits from a string in a text file.

#include <iostream>
using namespace std;

int main() {
  // open a file in read only mode
  FILE* textFile = fopen("text.txt", "r");
  char c; // c stores the last read character
  string code = ""; // empty string to store the password from the text
  while(true) // loop to read characters in the text file
    c = getc(textFile); // reads character
    if(feof(textFile)) // if end of file reached, stop reading

    if(isdigit(c)) // if digit found
      // push read char back into stream so it can be stored
      c = ungetc(c, textFile);
      while(true) // loop to store digits
        c = getc(textFile); // reads character
        // if end of file reached, or if c is not a digit
        if(feof(textFile) || !isdigit(c))
          // push non-digit back into stream and break out of loop
          ungetc(c, textFile);
        // else concatenate digit
        code = code + c;
  // print digits found
  cout << "The secret password is: " << code;
  return 0;

Related functions



View all Courses

Keep Exploring