Tuesday, July 14, 2009

A program in c........?

i ran a program in c:





#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;


int main()


{


int a,b,c;


char ch;


printf("enter the values");


scanf("%d %d",%26amp;a,%26amp;b);


printf("press + for addition\n\n press- for subtraction");


printf("press * for multiplication\n\npress / for division");


printf("enter your choice");


ch=getchar();//note this step





switch(ch)


{


case'+':c=a+b;


printf("sum=%d",c);


break;





case'-':c=a-b;


printf("difference=%d",c);


break;





case'*':c=a*b;


printf("product=%d,c);


break;





case'/':c=a/b;


printf("division=%d",c);


break;





default:


printf"wrong choice";


break;





}


getch();


return 0;


}


the problem is that the output of this program prints the default statement without waiting for the user to enter a choice....why??


also plzzz tell me how is ansi c different from normal c....say from turbo c??? delete

A program in c........?
I do too: when you scanf the values, that function (scanf) leaves the carriage-return (= you pressing ENTER) in the buffer. You expect to getchar() one of the operators, but instead you read that carriage return...
Reply:Yeah, you need to fflush() before you getch()
Reply:i know it
Reply:I took a quick look at your program (so I might have skipped something...) and it seems just fine. Maybe you need to clean the keyboard buffer for sometimes pressing certain keys sends more than one signal and the programs takes it as if you already pressed something.





To do that insert this line:





printf("enter your choice");


fflush(stdin); //%26lt;%26lt;%26lt;this one


ch=getchar();





About your other question... ANSI is an organization dedicated to the creation of standards, thus ANSI C is the standarized version of C programming language... as far as I know that is normal C... a different thing might be C++ which is object oriented and uses "cin" instead of "scanf" for example.





Turbo C is a program to edit and compile C programs... a program to make programs.
Reply:This is because we press the enter key after the scanf inputs are given this gets stored in the stdin buffer the getchar takes this as an input and shows the default value as answer.The best way is to clear the stdin buffer before executing the getchar statement.


ie:


fflush(stdin);


ch=getchar();

yu gi oh cards

No comments:

Post a Comment