Thread: Stdin buffer

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    3

    Stdin buffer

    Hi

    Can you help me understand with some level of detail (I guess that we overflow the stdin buffer on purpose, however the details escape me) what leads to the output of the code below for an input of "ululul" to be "ULULUL" instead of what I would expect to be "uUlLuUlLuUlL"?


    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int main()
    {
    	char c;
    	printf("Insert a word [Press enter to finish]\n");
    	//fflush(stdin);
    	do
    	{
    		scanf("%c", &c);
    		printf("%c", toupper(c));
    	}while(c != '\n');
    	return(0);
    }
    Last edited by euonym; 12-14-2010 at 09:01 PM.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Why would it? You'd have to use printf("%c%c", c, toupper(c));

    Also, void main() is bad as well as fflush(stdin);
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Dec 2010
    Posts
    3
    I'm sorry about that, you are correct.
    Still, can you help me understand why it doesn't process one char at a time, or why it doesn't ignore all but the last char?

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    But it does process one character at a time. Type any character and press enter. Then run it with a different length input. The only difference is when you press enter. Your experiment results mean that stdin is line buffered. In other words, scanf will read until a whole line is in stdin and then only return the first character. Subsequent calls to scanf will be streamed from stdin, until after the '\n' character is encountered.

  5. #5
    Registered User
    Join Date
    Dec 2010
    Posts
    3
    Thank you for the concise explanation.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 04:25 AM
  2. Function call from another .c module
    By Ali.B in forum C Programming
    Replies: 14
    Last Post: 08-03-2009, 11:45 AM
  3. stdin buffer size
    By Kempelen in forum C Programming
    Replies: 6
    Last Post: 03-16-2009, 03:06 PM
  4. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  5. Console Screen Buffer
    By GaPe in forum Windows Programming
    Replies: 0
    Last Post: 02-06-2003, 05:15 AM