PDA

View Full Version : I have problem in scanf




vavdiyaharesh
May 17, 2008, 08:16 AM
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



toddburch
May 17, 2008, 08:31 AM
Please use and 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.

newb16
May 23, 2008, 06:40 AM
Did you try scanf("%f",...) instead of "%f\n" ?

vavdiyaharesh
May 26, 2008, 12:11 AM
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.