C++ ungetwc()

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

The ungetwc() function is defined in <cwchar> header file.

ungetwc() prototype

wint_t ungetwc( wint_t ch, FILE* stream );

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

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

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

For both text and binary stream, a successful call to ungetwc 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 ungetwc().


ungetwc() Parameters

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

ungetwc() Return value

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

Example: How ungetwc() function works?

#include <cwchar>
#include <clocale>
#include <cwctype>
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
	setlocale(LC_ALL, "en_US.UTF-8");

	wint_t c;
	long value = 0;
	wchar_t str[] = L"\u0037\u0031\u0039\u00b6\u03ee";
	FILE *fp = fopen("file.txt", "r+");

	fputws(str,fp);
	rewind(fp);
	while(1)
	{
		c = fgetwc(fp);
		if (iswdigit(c))
		value = value*10 + c - L'0';
		else
		break;
	}
	ungetwc(c, fp);

	cout << "Value = " << value << endl;
	fclose(fp);
	return 0;
}

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

Value = 719