Thread: getchar() with an unbuffered stdin

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    217

    getchar() with an unbuffered stdin

    Code:
    #include <stdio.h>
    
    int main() {
    
        setvbuf(stdin, NULL, _IONBF, 0);
    
        int input;
        input = getchar();
    
        printf("\n%c", input);
    
        return 0;
    }
    The setvbuf statement is supposed to disable the buffering for the stdin stream.
    And getchar reads 1 character from the stdin.

    So I expected this program to reach the printf statement as soon as I enter a character in the console.

    But that does not happen. The program pauses at getchar and waits for it to read until I press the return_key. As though stdin is line buffered.

    Why does that happen? Am I not allowed to change how the stdin is buffered?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,706
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2018
    Posts
    217
    Quote Originally Posted by Salem View Post
    Which OS/Compiler are you using?
    I had just read about streams. I had read that the stdin was line buffered in my compiler. So I thought the reason getchar() didn't immediately read the character was because of this line buffering. I just wanted to clarify that.

    Thanks for the link. So the reason getchar() doesn't immediately read is not because of how stdin is buffered.. but a limitation of when input is added to the stdin..?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,706
    Depending on your platform, stdin can also be buffered in OS driver layer as well.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Sep 2018
    Posts
    217
    I understood, thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 12-03-2015, 03:19 AM
  2. Replies: 40
    Last Post: 06-28-2012, 12:53 PM
  3. problem in using getchar() insted of fflush(stdin)
    By fredsilvester93 in forum C Programming
    Replies: 1
    Last Post: 12-24-2011, 08:43 AM
  4. Newbie Question - fflush(stdin) & fpurge(stdin) on Mac and PC
    By tvsinesperanto in forum C Programming
    Replies: 34
    Last Post: 03-11-2006, 12:13 PM
  5. Using getc(stdin) or getchar(c)
    By daedenilus in forum C Programming
    Replies: 11
    Last Post: 11-13-2005, 01:00 AM

Tags for this Thread