#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    6
    Rep Power
    0

    Reason of output in C program ?


    What is the reason of following output in C program ?
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
    int a,b,sum;
    clrscr();
    printf("Enter 1st number");
    scanf("%d",&a);
    printf("Enter 2nd number:");
    scanf("%d",&b);
    sum=a+b;
    printf("The sum of 2 numbers are %d",sum);
    getch();
    }
    Output
    Enter 1st number 5 6
    Enter 2nd numberThe sum of 2 numbers are 11

    When i am providing 5 and 6 on the same line, then instead of waiting for the 2nd number it is jumping directly to the next message as given above.
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,216
    Rep Power
    2222
    It doesn't have to wait for the second number since you've already entered it. If you want it to wait, then don't enter the second number until after the second prompt.
  4. #3
  5. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,116
    Rep Power
    1803

    Lightbulb


    Standard input is line buffered so that scanf() does not return anything until there is a <newline> in the input buffer.

    For scanf() whitespace is a field delimiter, so the scanf() call consumes the first value, leaving the second buffered. On the second scanf() call, it returns immediately because there is a <newline> already buffered. Note that the <newline> is not consumed by %d, so a subsequent input call will also return immediately.

    One Solution:

    Code:
    printf("Enter 1st number");
    scanf("%d",&a);
    while( getchar() != '\n' ) { /* do nothing*/ }
    
    printf("Enter 2nd number:");
    scanf("%d",&b);
    while( getchar() != '\n' ) { /* do nothing*/ }
    Ideally you would wrap the input and buffer flushing into a single function to avoid repetition:
    Code:
    int enterDecimal( void )
    {
        int val ;
    
        scanf( "%d", &val ) ;
    
        while( getchar() != '\n' ) 
        { 
            // do nothing
        }
    
        return val ;
    }
    then
    Code:
    printf("Enter 1st number");
    a = enterDecimal() ;
    
    printf("Enter 2nd number:");
    b = enterDecimal() ;
    Last edited by clifford; January 8th, 2013 at 08:40 AM.

IMN logo majestic logo threadwatch logo seochat tools logo