Thread: scanf and printf precedence

  1. #1
    Registered User
    Join Date
    Jun 2005
    Posts
    3

    Question scanf and printf precedence

    Hey,
    does anyone knows why scanf always comes before any printf? how do I print any thing before an input?

    PHP Code:
    int ab;
      
    printf("Enter 2 numbers:");
      
    scanf("%d %d", &a, &b);
      
    printf("%d %d"ab); 
    and it comes out:
    12 47
    Enter 2 numbers:12 47

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Flush the output stream before calling scanf.
    Code:
    int a, b;
    printf("Enter 2 numbers:");
    fflush( stdout );
    scanf("%d %d", &a, &b);
    printf("%d %d", a, b);
    If you print with a newline at the end, it will flush the output. Without, it may or may not. It doesn't have to. So it's really dependant on your OS / compiler / whatever it feels like.
    Code:
    printf("foo\n"); /* flushes output... */
    printf("bar" ); /* doesn't */
    fflush is only designed for output streams. You can't flush input with it. Or rather, it's undefined behaviour if you try it.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    3
    works like a charm. thank you

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 03-05-2009, 10:25 AM
  2. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  3. Newb Help: Full Arrays and Functions
    By LycanGalen in forum C Programming
    Replies: 5
    Last Post: 01-31-2008, 08:35 PM
  4. Please help debug
    By Wexy in forum C Programming
    Replies: 2
    Last Post: 11-11-2002, 12:40 AM
  5. help with switch statements
    By Wexy in forum C Programming
    Replies: 3
    Last Post: 11-06-2002, 05:44 PM