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)
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.
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.
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.
This code extracts digits from a string in a text file.
#include <iostream>#include<cstdio>#include<cctype>using namespace std;int main() {// open a file in read only modeFILE* textFile = fopen("text.txt", "r");char c; // c stores the last read characterstring code = ""; // empty string to store the password from the textwhile(true) // loop to read characters in the text file{c = getc(textFile); // reads characterif(feof(textFile)) // if end of file reached, stop reading{break;}if(isdigit(c)) // if digit found{// push read char back into stream so it can be storedc = 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 digitif(feof(textFile) || !isdigit(c)){// push non-digit back into stream and break out of loopungetc(c, textFile);break;}// else concatenate digitcode = code + c;}}}// print digits foundcout << "The secret password is: " << code;return 0;}