cinputoutputgetcharungetc

Ungetc() Not Ungetting Character


My code is extremely simple, but I figure that's best to figure out what's going on in my program. For some reason, I can't seem to get ungetc() to work properly, nor can I figure out it's purpose. Normally, ungetc() should return a character back into the stream or, at least, I think it should. For example, if I type ABC, getting three characters through getchar(), I would expect ungetc() to return one of the letters getchar() had returned. If I later call putchar(), I would expect B to be returned, since C was tossed back into the stream, but C was returned. I've tried both getchar() as well as getc() and run into the same issue.

Condensed version, I typed "ABC" into my program, expecting ungetc() to cause the putc() to return 'B', but all I get is C again. Why is this happening?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
    char c;
    c=getchar();
    c=getchar();
    c=getchar();
    ungetc(c, stdout);
    putchar(c);
}

Solution

    1. Removed the two unused headers.
    2. The type of the variable c should be int not char to match the functions used. It serves no purpose to assign values to c if they are not used. That said you can eliminate the variable entirely (point-free style).
    3. The program segfaults as it should be push c to stdin instead of stdout.
    4. Call getchar() after the ungetc() to demonstrate the property of interest otherwise you just print the previous read value.
    #include <stdio.h>
    
    int main(void) {
        getchar();
        getchar();
        ungetc(getchar(), stdin);
        putchar(getchar());
    }
    

    and example run:

    ABC
    C