simple scanf question

Discussion in 'C' started by xqwertyx, Feb 12, 2010.

  1. xqwertyx

    xqwertyx New Member

    Joined:
    Feb 12, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    main()
    {
    int fahr, celsius;
    int lower, upper, step;

    scanf("%d%d%d" , lower, upper, step);
    fahr = lower;

    while (fahr <= upper) {
    celsius = 5 / 9 * (fahr-32) ;
    printf("%d\t%d\n" , fahr, celsius);
    fahr = fahr +step;
    }
    }

    I just started learning C and wanted to play with scanf,,
    When i run the above code and type in numbers, the command prompt crashes..
    is this a problem with my code or computer?
    thank you
     
  2. Gene Poole

    Gene Poole New Member

    Joined:
    Nov 10, 2009
    Messages:
    93
    Likes Received:
    5
    Trophy Points:
    0
    Try a space between your "%d" s. Also, scanf uses the address of the variables so you need to prepend them with "&":

    Code:
      scanf("%d %d %d" , &lower, &upper, &step);
    
     
  3. murugaperumal

    murugaperumal New Member

    Joined:
    Feb 20, 2010
    Messages:
    15
    Likes Received:
    1
    Trophy Points:
    0
    Dear Friend,

    In the code
    scanf("%d%d%d",lower, upper, step);

    Here space between the "%d" is not must. You can give or no need. But "& " is must for each variable,which is used in the scanf.

    The correct code is

    Code:
       scanf("%d%d%d",&lower, &upper, &step); 
    
     
  4. vivekraj

    vivekraj New Member

    Joined:
    Feb 23, 2010
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    As muruga said,there is no rule to leave space between the format specifiers such as %d in your example.According to your program,you should use & before the lower,upper and step variables.Because,scanf expects the pointer as its argument after the format specifier.

    scanf will read the input and store the given input in the specified location pointed to by the pointer specified.

    If you use array,then there is no need to use &.Because,array generally points to the memory location directly.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice