C++ ungetc()

The ungetc() function in C++ push the previously read character back to the stream so that it could be read again.

The ungetc() function is defined in <cstdio> header file.

ungetc() prototype

int ungetc(int ch, FILE* stream);

The ungetc() function pushes the character ch back to the buffer associated with the file stream unless ch is equal to EOF. If ch is equal to EOF, the operation fails and there is no change in the stream.

Calls to ungetc() may fails if it is called more than once without any read or repositioning operation in the middle.

If a call to ungetc() is successful the end of file status flag feof is cleared.

For binary streams, a successful call to ungetc decrements the stream position indicator by one. If the stream position indicator is zero, the behavior is indeterminate.

For text stream, a successful call to ungetc modifies the stream position indicator in an unspecified manner. But it is guaranteed that after all pushed-back characters are retrieved with a read operation, the stream position indicator is equal to its value before calling ungetc().

ungetc() Parameters

  • ch: The character to be pushed back.
  • stream: File stream where the character is pushed back.

ungetc() Return value

  • On success, the ungetc() function returns the character ch.
  • On failure EOF is returned without changing the stream.

Example: How ungetc() function works?

#include <cstdio>
#include <cctype>
#include <iostream>
using namespace std;

int main()
	int c;
	long value = 0;
	char str[] = "101axc";

	FILE *fp = fopen("file.txt", "r+");

		c = fgetc(fp);
		if (isdigit(c))
			value = value*10 + c - '0';

	ungetc(c, fp);
	cout << "Value = " << value << endl;

	return 0;

When you run the program, a possible output will be:

Value = 101
Did you find this article helpful?