0

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);
}
2
  • 3
    ungetc is an INPUT function. Use ungetc(c, stdin);. BTW, all that does is put c back into the input buffer, so the next getchar will get that again. It doesn't change c. Commented Aug 21, 2024 at 3:00
  • 1
    Thanks for the response, it was very helpful. I tested ungetchar() by using it before each c=getchar() and it seems work. If I don't use unget() char, it cycles through the input stream. If I use unget() char after each getchar(), it stays on A, meaning A (or the first character) is going back on the buffer. Commented Aug 21, 2024 at 21:36

1 Answer 1

3
  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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.