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

    Join Date
    Mar 2013
    Posts
    6
    Rep Power
    0

    Strange result with scanf() function.why?


    Code:
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
       char name[5];
       int price[5];
       int pages[5];     
       int i;
    
       for(i=0;i<5;i++)
       scanf("%c%d%d",&name[i],&price[i],&pages[i]);
       
       for(i=0;i<5;i++)
       printf("\n%c %d %d",name[i],price[i],pages[i]);
       getch();
        
    }
    
    
    output
    
    a 1 1
    b 2 2
    c 3 3        //till here it is taking input(first for loop)
    
    
    
    a 1 1        //from here it is printing(second for loop)
    
     3935864 2
    b 2 2
    
     2007342877 2007403733
    c 3 3
    i am able to provide input values only for 3 times but in for loop i have written code to enter input for five times.
    when trying to give the input values fourth time, it is directly printing my given values that in strange order.why?
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Location
    Iran
    Posts
    149
    Rep Power
    140
    Hi,

    When you push the enter button in the terminal and therefore inserting a new line character. The next call to scanf continue to read what is in the buffer (that is, the new line from the previous entry in the terminal), you can skip that from your result by putting a space character before %c in your scanf call.

    So instead of
    Code:
    scanf("%c%d%d",&name[i],&price[i],&pages[i]);
    You write
    Code:
    scanf(" %c%d%d",&name[i],&price[i],&pages[i]);
    Regards,
    Dariyoosh
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    6
    Rep Power
    0
    yaaa....its working.thankyou verymuch. :)

IMN logo majestic logo threadwatch logo seochat tools logo