I have problem in scanf

Discussion in 'Mac Programming' started by vavdiyaharesh, May 17, 2008.

  1. vavdiyaharesh macrumors newbie

    Joined:
    May 15, 2008
    #1
    Hello
    i m doing one small program that takes two number and one operator and does some calculation
    following is my code
    #include <stdio.h>
    #include "Fraction.h"

    main()
    {

    Fraction *frac=[[Fraction alloc] init];
    float a;
    printf("Enter first number:");
    scanf("%f\n",&a);
    float b;
    //printf("Enter second number:");
    //scanf("%f\n\n",&b);
    printf("Press from the following\n");
    printf("1 for Addition\n");
    printf("2 for Substcration\n");
    printf("3 for Multiplication\n");
    printf("4 for Division\n");
    int op;
    scanf("%d\n",&op);


    printf("%f %f %d\n",a,b,op);
    [frac calc: a : b : op];
    [frac free];

    }


    but whenever execute this program
    actually this program should give like "Enter first number " & then "Enter Second number " and "Enter operator" but it gives me like enter first number then i have to enter two number then it goes to next and then enter second number and then enter your choice
    so it takes 4 values instead of 3
    pls help me
     
  2. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #2
    Please use [code] and [/code] tags in the future.

    scanf() will typically leave the newline character in the input buffer. You can use getchar() to put it off prior to doing the second scanf() (which you currently have commented out).

    Your description of the problem is, like, incoherent.
     
  3. newb16 macrumors regular

    Joined:
    Feb 27, 2008
    #3
    Did you try scanf("%f",...) instead of "%f\n" ?
     
  4. vavdiyaharesh thread starter macrumors newbie

    Joined:
    May 15, 2008
    #4
    Yes buddy,
    Before i have written "%f\n" and thats why it asks for values twice and then after i have removed "\n" then it works perfectly.

    Thankx buddy.
     

Share This Page