i just want to put more than one character through the (get char) or by any other way, this is a simple calculator program using switch cases condition but cant choose a case with more than one input to the getch function for ex: 10,11....
#include <stdio.h>
#include <conio.h>
void plus_func();
void menus_func();
void mul_func();
void div_func();
void modulus_func();
void shiftleft_func();
void shiftright_func();
void and_func();
void or_func();
void not_func();
void doubleand_func();
void doubleor_func();
void notequal_func();
void xor_func();
void main(void){
int x,y, res;
int m;
int op1;
int op2;
int op3;
int i=0;
int k;
while(i==0){
printf("Enter any key to start the calculator function program or escape to exit it \n");
k=getch();
if(k!=0x1b)
{
printf("enter the first num or press escape to exit \n");
x=getch();
if(x==0x1b)
{
break;
}
else
{
op1=x-48;
}
printf("enter the second num or press escape to exit \n");
y=getch();
if(y==0x1b)
{
break;
}
else
{
op2=y-48;
}
printf("enter the type of the operation \n",m);
m=getch();
if(m==0x1b)
{
break;
}
else
{
op3=m-48;
}
switch(op3)
{
case 1: plus_func(op1,op2);break;
case 2: menus_func(op1,op2);break;
case 3: mul_func(op1,op2);break;
case 4: div_func(op1,op2);break;
case 5: modulus_func(op1,op2);break;
case 6: shiftleft_func(op1,op2);break;
case 7: shiftright_func(op1,op2);break;
case 8: and_func(op1,op2);break;
case 9: or_func(op1,op2);break;
case 10: not_func(op1,op2);break;
case 11: doubleand_func(op1,op2);break;
case 12: doubleor_func(op1,op2);break;
case 13: notequal_func(op1,op2);break;
case 14: xor_func(op1,op2);break;
default: printf("error");
break;
}
}
else
{
break;
}
}
}
void plus_func(int a, int b)
{
int c;
c=a+b;
printf("the result is %d \n",c);
}
void menus_func(int a, int b)
{
int c;
c=a-b;
printf("the result is %d \n",c);
}
void mul_func(int a, int b)
{
int c;
c=a*b;
printf("the result is %d \n",c);
}
void div_func(int a, int b)
{
int c;
c=a/b;
printf("the result is %d \n",c);
}
void modulus_func(int a, int b)
{
int c;
c=a%b;
printf("the result is %d \n",c);
}
void shiftleft_func(int a, int b){
int c;
c=a<<b;
printf("the result is %d \n",c);
}
void shiftright_func(int a, int b)
{
int c;
c=a>>b;
printf("the result is %d \n",c);
}
void and_func(int a, int b)
{
int c;
c=a&b;
printf("the result is %d \n",c);
}
void or_func(int a, int b)
{
int c;
c=a|b;
printf("the result is %d \n",c);
}
void not_func(int a, int b)
{
int c;
c=a+b;
c=~c;
printf("the result is %d \n",c);
}
void doubleand_func(int a, int b)
{
int c;
c=a&&b;
printf("the result is %d \n",c);
}
void doubleor_func(int a, int b)
{
int c;
c=a||b;
printf("the result is %d \n",c);
}
void notequal_func(int a, int b)
{
int c;
c=a+b;
c=!c;
printf("the result is %d \n",c);
}
void xor_func(int a, int b)
{
int c;
c=a^b;
printf("the result is %d \n",c);
}
This function will capture a number of digits and concatenate them into a value. To conserve space only the plus_func is include in the code and switch. The function accepts the number of digits, a sign flag and a pointer to the value. It returns an integer to indicate that ESC was pressed.
With this, each input is a fixed width. To input 3, 03 must be typed.
#include <stdio.h>
#include <conio.h>
int getint ( unsigned int digits, int sign, int *value) {
int ch = 0;
unsigned int first = digits;
*value = 0;//set to zero
while ( digits) {
while ( ( ch = getch()) < '0' || ch > '9') {
if ( ch == '-' && sign == 1 && first == digits) {// allow for negative numbers
sign = -1;
putchar ( '-');
}
if ( ch == 0x1b) {
return 1;
}
}
putchar ( ch);
*value *= 10;
*value += ch - '0';//concatenate the digits
digits--;
}
if ( sign) {
*value *= sign;
}
return 0;
}
void plus_func(int a, int b)
{
int c = 0;
c = a + b;
printf ( "\nthe result is %d\n", c);
}
int main()
{
int i = 0;
int op1 = 0;
int op2 = 0;
int op3 = 0;
unsigned int digits = 2;
do {
printf("\nenter the first %u digit num or press escape to exit \n", digits);
if ( getint ( digits, 1, &op1)) {
break;
}
printf("\nenter the second %u digit num or press escape to exit \n", digits);
if ( getint ( digits, 1, &op2)) {
break;
}
printf("\nenter the type of the operation from 01 to 14\n");
if ( getint ( digits, 0, &op3)) {
break;
}
switch ( op3) {
case 1:
plus_func ( op1, op2);
break;
default:
printf ( "error\n");
break;
}
} while ( i == 0);
return 0;
}
scanf("%d",&k);
is what you need.
More safe:
scanf_s("%d",&k);
Well, getch () cannot take more than two characters. You can use getline (), but I don't think that is what you need. You are reading numbers, not characters. So do
scanf ("%d", &k);
or use scanf_s as mentioned in #DivinCodino's answer. Also, still if you want to read characters, use getline as mentioned above or use scanf:
scanf (" %c", &k);
and declare k as
char k;
Also, your current program will not work properly as it is trying to read integers using getch, which is designed only for reading characters.
After making the changes above, the code is:
#include <stdio.h>
#include <conio.h>
void plus_func();
void menus_func();
void mul_func();
void div_func();
void modulus_func();
void shiftleft_func();
void shiftright_func();
void and_func();
void or_func();
void not_func();
void doubleand_func();
void doubleor_func();
void notequal_func();
void xor_func();
void main(void){
int x,y, res;
int m;
int op1;
int op2;
int op3;
int i=0;
int k;
while(i==0){
printf("Enter any key to start the calculator function program or escape to exit it \n");
k=getch();
if(k!=0x1b)
{
printf("enter the first num or press escape to exit \n");
scanf ("%d", &x);
if(x==0x1b)
{
break;
}
else
{
op1=x-48;
}
printf("enter the second num or press escape to exit \n");
scanf ("%d", &y);
if(y==0x1b)
{
break;
}
else
{
op2=y-48;
}
printf("enter the type of the operation \n",m);
scanf ("%d", &m);
if(m==0x1b)
{
break;
}
else
{
op3=m-48;
}
switch(op3)
{
case 1: plus_func(op1,op2);break;
case 2: menus_func(op1,op2);break;
case 3: mul_func(op1,op2);break;
case 4: div_func(op1,op2);break;
case 5: modulus_func(op1,op2);break;
case 6: shiftleft_func(op1,op2);break;
case 7: shiftright_func(op1,op2);break;
case 8: and_func(op1,op2);break;
case 9: or_func(op1,op2);break;
case 10: not_func(op1,op2);break;
case 11: doubleand_func(op1,op2);break;
case 12: doubleor_func(op1,op2);break;
case 13: notequal_func(op1,op2);break;
case 14: xor_func(op1,op2);break;
default: printf("error");
break;
}
}
else
{
break;
}
}
}
void plus_func(int a, int b)
{
int c;
c=a+b;
printf("the result is %d \n",c);
}
void menus_func(int a, int b)
{
int c;
c=a-b;
printf("the result is %d \n",c);
}
void mul_func(int a, int b)
{
int c;
c=a*b;
printf("the result is %d \n",c);
}
void div_func(int a, int b)
{
int c;
c=a/b;
printf("the result is %d \n",c);
}
void modulus_func(int a, int b)
{
int c;
c=a%b;
printf("the result is %d \n",c);
}
void shiftleft_func(int a, int b){
int c;
c=a<<b;
printf("the result is %d \n",c);
}
void shiftright_func(int a, int b)
{
int c;
c=a>>b;
printf("the result is %d \n",c);
}
void and_func(int a, int b)
{
int c;
c=a&b;
printf("the result is %d \n",c);
}
void or_func(int a, int b)
{
int c;
c=a|b;
printf("the result is %d \n",c);
}
void not_func(int a, int b)
{
int c;
c=a+b;
c=~c;
printf("the result is %d \n",c);
}
void doubleand_func(int a, int b)
{
int c;
c=a&&b;
printf("the result is %d \n",c);
}
void doubleor_func(int a, int b)
{
int c;
c=a||b;
printf("the result is %d \n",c);
}
void notequal_func(int a, int b)
{
int c;
c=a+b;
c=!c;
printf("the result is %d \n",c);
}
void xor_func(int a, int b)
{
int c;
c=a^b;
printf("the result is %d \n",c);
}
This code still does not work, but I haven't done any changes except changing getch to scanf.
Related
I am in 10th grade and was trying to build a simple calculator in c. Although I've checked multiple times even though the code was correct as per the syntax, it is not showing the proper output. Multiplication gives an output of 0, and addition/subtraction gives output as the first number input. tried alternative methods, yet everything results in the same output
please try to troubleshoot the code explain me where am i going wrong.
#include <stdio.h>
#include <math.h>
//Creating a simple calculator in c
//add func
int add(int n1, int n2)
{
int result = n1 + n2;
return(result);
}
//subtract func
int subtract(int n1, int n2)
{
int result = n1 - n2;
return(result);
}
//divide func
int divide(int n1, int n2)
{
int result = n1 / n2;
return(result);
}
//multiply func
int multiply(int n1, int n2)
{
int result = n1 * n2;
return(result);
}
int main()
{
int num1, num2, ans;
char op;//op means operator
//use input
printf("Enter first number: ");
scanf("%d", &num1); //takes first number
printf("\nEnter second number: ");
scanf("%d", &num2); //takes second number
printf("\nEnter operation: ");
scanf("%s", &op); //takes an operator character like '+', '-', '/', '*'
//checks which operator has been inputted
if (op =='+')
{
int ans = add(num1, num2);
printf("Answer: %d", ans);
}
else if (op=='-')
{
ans = num1-num2;
printf("Aswer: %d", ans);
}
else if (op=='/')
{
ans = divide(num1, num2);
printf("Answer: %d",ans);
}
else if (op == '*')
{
ans = multiply(num1, num2);
printf("Answer: %d",ans);
}
else //exits with error if input instead of + - / *
{
printf("Invalid operator!");
}
return 0;
}
A few issues ...
As mentioned in the top comments, char op; will have UB (undefined behavior) when we do: scanf("%s",&op); because the %s adds a string terminator 0x00 at the end. So, op must be [at least] two chars in length.
A switch/case is better than an if/else "ladder".
We can simplify the code with just a single printf.
Here is the refactored code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//Creating a simple calculator in c
//add func
int
add(int n1, int n2)
{
int result = n1 + n2;
return (result);
}
//subtract func
int
subtract(int n1, int n2)
{
int result = n1 - n2;
return (result);
}
//divide func
int
divide(int n1, int n2)
{
int result = n1 / n2;
return (result);
}
//multiply func
int
multiply(int n1, int n2)
{
int result = n1 * n2;
return (result);
}
int
main()
{
int num1, num2, ans;
#if 0
char op; // op means operator
#else
char op[10]; // op means operator
#endif
// user input
printf("Enter first number: ");
scanf("%d", &num1);
printf("\nEnter second number: ");
scanf("%d", &num2);
// takes an operator character like '+', '-', '/', '*'
printf("\nEnter operation: ");
#if 0
scanf("%s", &op);
#else
scanf("%s", op);
#endif
// checks which operator has been inputted
switch (op[0]) {
case '+':
ans = add(num1, num2);
break;
case '-':
ans = subtract(num1,num2);
break;
case '/':
ans = divide(num1, num2);
break;
case '*':
ans = multiply(num1, num2);
break;
default: // exits with error if input instead of + - / *
printf("Invalid operator!");
exit(1);
break;
}
printf("Answer: %d\n", ans);
return 0;
}
In the above code, I've used cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Note: this can be cleaned up by running the file through unifdef -k
Your primary issue is a misuse of scanf. (A reasonable argument can be made that any use of scanf is a misuse! You would do well to forget that scanf exists, since using it will likely hinder your learning of the language.) Parameters like this should really be taken from the command line arguments rather than the input stream, but the primary reason I'm adding this answer (it's really a comment, but it's hard to format comments well) is to demonstrate one method for reducing the duplication in your code. For each operator, you have boilerplate that doesn't need to exist. eg:
#include <stdio.h>
#include <stdlib.h>
int add(int n1, int n2) { int result = n1 + n2; return result; }
int subtract(int n1, int n2) { int result = n1 - n2; return result; }
int divide(int n1, int n2) { int result = n1 / n2; return result; }
int multiply(int n1, int n2) { int result = n1 * n2; return result; }
int
main(int argc, char **argv)
{
int num1 = argc > 1 ? strtol(argv[1], NULL, 0) : 1;
int op = argc > 2 ? argv[2][0] : '+';
int num2 = argc > 3 ? strtol(argv[3], NULL, 0) : 1;
int (*f)(int, int);
switch(op) {
case '+': f = add; break;
case '-': f = subtract; break;
case '/': f = divide; break;
case '*': f = multiply; break;
default:
fprintf(stderr, "invalid operator\n");
return 1;
}
int ans = f(num1, num2);
printf("%d %c %d = %d\n", num1, op, num2, ans);
return 0;
}
Note that returning int from a "divide" function is probably a terrible idea. It's not inherently wrong, but you may be surprised to find that divide(1, 2) returns 0. Make sure you understand that.
You can also skip the switch entirely by using a lookup table:
int (*g[])(int, int) = {
['+'] = add,
['-'] = subtract,
['/'] = divide,
['*'] = multiply,
};
if( ! op || ! strchr("+-/*", op) ){
fprintf(stderr, "invalid operator\n");
return 1;
}
printf("%d %c %d = %d\n", num1, op, num2, g[op](num1, num2));
I implemented an RPN Calculator in C. Now I want to output the current iteration meaning
Iteration 1: Contents: [5, 5]
Iteration 2: Contents: [25]
I am not quite sure how i am going to print them. I tried Printing them in the main function, but the output was coming
Iteration 1: Contents: 5
Iteration 2: Contents: 5
10
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = 0;
void makeEmpty()
{
top = 0;
}
bool isEmpty()
{
return top == 0;
}
bool isFull()
{
return top == MAX_SIZE;
}
void push(int value)
{
stack[top++] = value;
}
int pop()
{
if(isEmpty())
{
printf("Not enough operands in expression\n");
exit(EXIT_FAILURE);
}
return stack[--top];
}
//adds 2 integers
int add(int a, int b)
{
return a + b;
}
//subtracts 2 integers
int sub(int a, int b)
{
return a - b;
}
//multiplies 2 integers
int mul(int a, int b)
{
return a * b;
}
//divides 2 integers
int divide(int a, int b)
{
return a / b;
}
int main(void)
{
char ch;
while(1)
{
//Emptying the stack before the user enters another expression
makeEmpty();
printf("Enter an RPN expression: ");
//Reads expression from user
scanf("%c", &ch);
//parse all characters until a newline is reached
while(1)
{
if(ch == '\n')
break;
//if character is an integer
if(ch >= 48 && ch <= 57)
{
if(!isFull())
{
//convert char to int and push integer onto stack
printf("Iteration %d: Contents: %d \n", (top+1), (ch-48));
push(ch - 48);
}
else
{
//stack ran out of space, print error and exit program
printf("Expression is too complex\n");
exit(EXIT_FAILURE);
}
}
switch(ch)
{
case '+':
push(add(pop(), pop()));
break;
case '-':
push(sub(pop(), pop()));
break;
case '*':
push(mul(pop(), pop()));
break;
case '/':
push(divide(pop(), pop()));
break;
case '=':
printf("%d\n", pop());
break;
}
//get next character
scanf("%c", &ch);
}
}
return 0;
}
You can easily workaround it in your program without creating temporary stacks:
void print_stack(void)
{
printf("[");
for(int index = top -1; index >= 0; index--)
{
printf("%d%s", stack[index], index ? ", " : "");
}
printf("]\n");
}
This is a random math problem generator program.
The problem is my input answer and the real answer keeps returning 0.
What's the problem here? I can't find out why.
Here's the code step by step...
import libraries
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
calling functions
int getRandNum(int i, int lower, int upper, int randNum);
int getRandOp(int i, int opSel, char randOp);
int getRealAnswer(char randOp, int randNum1, int randNum2, int realAnswer);
void showQuestion(int i, int randNum1, int randOp, int randNum2, int realAnswer, int
userAnswer);
int getUserAnswer(int userAnswer);
void answerCompare(int realAnswer, int userAnswer);
main() function
int main(void) // main fucntion
{
int i;
int randNum1, randNum2;
int userAnswer, realAnswer;
char randOp;
srand(time(NULL));
for (i = 1; i <= 5; i++)
{
showQuestion(i, randNum1, randOp, randNum2, realAnswer, userAnswer);
getUserAnswer(userAnswer);
getRealAnswer(randNum1, randNum2, randOp, realAnswer);
answerCompare(realAnswer, userAnswer);
printf("Real Answer = %d User Answer = %d\n\n", realAnswer, userAnswer);
}
return 0;
}
getRandNum() function
int getRandNum(int i, int lower, int upper, int randNum) // get random number within range using rand() function
{
lower = (20 * (i - 1)) + 1;
upper = 20 * I;
randNum = (rand() % (upper - lower + 1)) + lower;
return randNum;
}
getRandOp() function
int getRandOp(int i, int opSel, char randOp) // get random operator within list using rand() function
{
char opList[4] = {'+', '-', '*', '/'};
opSel = rand() % 4;
randOp = opList[opSel];
return randOp;
}
getRealAnser() function
int getRealAnswer(char randOp, int randNum1, int randNum2, int realAnswer) // get real answer of the problem (problematic part: always returns 0)
{
switch (randOp)
{
case '+':
realAnswer = randNum1 + randNum2;
case '-':
realAnswer = randNum1 - randNum2;
case '*':
realAnswer = randNum1 * randNum2;
case '/':
realAnswer = randNum1 / randNum2;
default:
break;
}
return realAnswer;
}
showQuestion() function
void showQuestion(int i, int randNum1, int randOp, int randNum2, int realAnswer, int userAnswer) // print out math question
{
int randNum, opSel, lower, upper;
printf("##### Question Number %d #####\n", I);
randNum1 = getRandNum(i, lower, upper, randNum);
randOp = getRandOp(i, opSel, randOp);
randNum2 = getRandNum(i, lower, upper, randNum);
realAnswer = getRealAnswer(randNum1, randNum2, randOp, realAnswer);
printf("%d %c %d = ", randNum1, randOp, randNum2);
}
getUserAnswer() function
int getUserAnswer(int userAnswer) // user input answer of the problem (problematic part: always returns 0)
{
userAnswer = scanf("%d", &userAnswer);
return userAnswer;
}
answerCompare() function
void answerCompare(int realAnswer, int userAnswer) // compare user answer and real answer of the problem and print result
{
if (userAnswer == realAnswer)
{
printf("You are correct!\n");
}
else if (userAnswer != realAnswer)
{
printf("You are wrong!\n");
}
else
{
printf("Error! Invalid Comparison!\n");
}
}
Change getUserAnswer to something like this:
int getUserAnswer()
{
int userAnswer = -1;
userAnswer = scanf("%d", &userAnswer);
return userAnswer;
}
And use it like this:
userAnswer = getUserAnswer();
Do something similar for real answer code.
Also the answerCompare can be simplified to an "if-else" structure since if the == fails by definition they are !=. (It would never reach the 'invalid comparison' code.)
Also in getRealAnswer you'll need breaks for each case or simply return in each case. As posted each operator falls through to next case.
You have to give, both of your functions, a pointer of int if you want to modify the value of a variable you have on main. So for example for the first function:
void getUserAnswer(int* userAnswer) // user input answer of the problem (problematic part: always returns 0)
{
*userAnswer = -1;
scanf("%d", &(*userAnswer)); // you don't need to store return value of scanf
}
int main (void) {
/* do stuff */
int userAnswer;
getUserAnswer(&userAnswer); // use func like this
/* do stuff */
return 0;
}
void getRealAnswer(char randOp, int randNum1, int randNum2, int* realAnswer) // get real answer of the problem (problematic part: always returns 0)
{
switch (randOp)
{
case '+': {
*realAnswer = randNum1 + randNum2;
} break;
case '-': {
*realAnswer = randNum1 - randNum2;
} break;
case '*': {
*realAnswer = randNum1 * randNum2;
} break;
case '/': {
*realAnswer = randNum1 / randNum2;
} break;
default:
break;
}
}
Passing a pointer to the variable you want to modify you don't need to return any value from your function, so I changed it to void
This question already has answers here:
What is easiest way to calculate an infix expression using C language?
(6 answers)
Simple library or implementation for a mathematical expression evaluator [closed]
(7 answers)
Closed 2 years ago.
I want to write a C function which takes string as input.
Example User Input:
"(1+2-3+(4+5))-7)"
The desired output is 2 as an integer. Basically I have to remove "("")" white spaces and compute the addition and subtraction operations.
if you want to this from Scratch you must parse your input for find priority, and transform each number(string) in number(int) for calcul. You can transform a string number in int number with atoi.
Exemple:
#include <stdio.h>
void add ();
void sub ();
void mul ();
void div ();
void sqr ();
void prime_factorization ();
void factorial ();
void sel_func (int);
int main (void)
{
int s;
Input:
printf("Input a number [ +(1), -(2), *(3), /(4), ^(5), prime factorization(6), !(7)] : ");
scanf("%d",&s);
if (s > 7 | s < 1){
printf("Please input again\n");
goto Input;
}
sel_func (s);
goto Input;
}
void sel_func (int s)
{
void (*fptr)(void);
switch (s){
case 1:
fptr = add;
break;
case 2:
fptr = sub;
break;
case 3:
fptr = mul;
break;
case 4:
fptr = div;
break;
case 5:
fptr = sqr;
break;
case 6:
fptr = prime_factorization;
break;
case 7:
fptr = factorial;
break;
}
fptr();
}
void add ()
{
int a, b;
printf("Input two numbers : ");
scanf("%d%d", &a,&b);
printf("Result = %d\n", a + b);
}
void sub ()
{
int a, b;
printf("Input two numbers : ");
scanf("%d%d", &a,&b);
printf("Result = %d\n" , a - b);
}
void mul ()
{
int a, b;
printf("Input two numbers : ");
scanf("%d%d", &a,&b);
printf("Result = %d\n", a * b);
}
void div ()
{
int a, b;
printf("Input two numbers : ");
scanf("%d%d", &a,&b);
printf("Result = %d\n", a / b);
}
void sqr (){
int exp, base, i;
int result = 1;
printf("Input base : ");
scanf("%d",&base);
printf("Input exp : ");
scanf("%d",&exp);
for (i = 0; i < exp; ++i)
result *= base;
printf("%d^%d = %d\n",
base,exp,result);
}
void prime_factorization ()
{
int n;
while (1){
printf("Input a number : ");
scanf("%d",&n);
if(n < 2)
return;
}
int p = 2;
int primes[20];
int index = 0;
int i;
while (1 != n){
if (0 == (n%p)){
n = n/p;
primes[index] = p;
++index;
p = 2;
} else {
++p;
}
}
if(1 == index){
printf("Prime number\n");
} else {
for (i = 0; i < index - 1; ++i)
printf("%d*", primes[i]);
printf("%d\n", primes[i]);
}
return;
}
void factorial ()
{
int a, b;
int sum = 1;
printf("Input a number : ");
scanf("%d", &b);
for (a = 1; a <= b; ++a)
sum *= a;
printf("%d!=%d\n",b,sum);
}
I'm trying to make a C program to evaluate postfix expressions and when doing so an unwanted symbol is being printed on the screen for the input 45+.
P.S. Please tell me the mistake (except of that gets() I am studying right now how to use fgets())
// to Evaluate a postfix expression
#include<stdio.h>
#include<conio.h>
int is_operator(char);
void answer();
char stack[100];
int top =-1;
void push(char);
char pop();
void main()
{
char postfix[100],item;
int i=0;
clrscr();
printf("Enter Postfix Expression");
gets(postfix);
while(postfix[i]!='\0')
{
item=postfix[i];
if(is_operator(item)==2)
{
push(item);
}
if(is_operator(item)==1)
{
char op;
int n1,n2,n3;
op=item;
n1=pop();
n2=pop();
switch(op)
{
case '+':
n3=n1+n2;
case '-':
n3=n1-n2;
case '*':
n3=n1*n2;
case '/':
n3=n1/n2;
}
push(n3);
}
i++;
}//end while
answer();
getch();
}
void push(char c)
{
top++;
stack[top]=c;
}
char pop()
{
char c;
c=stack[top];
top--;
return(c);
}
int is_operator(char i)
{
char ch=i;
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
{
return(1);
}
else
{
return(2);
}
}
void answer()
{
char ans;
ans=stack[top];
printf("Answere is %c",ans);
}
There are a lot of mistakes in your code.Try to properly type cast.
Go through comments to understand the mistakes.
Go through this for understanding character pointer and arrays.
// to Evaluate a postfix expression
#include<stdio.h>
int is_operator(char);
void answer();
int stack[100];//Use integer array since operands are integer
int top =-1;
void push(int);//Arguments changed to integer type since the stack is integer
int pop(); //Return type to integer
void main()
{
char* postfix;//Use character pointer for iterating through loop smoothly
int item;
int i=0;
printf("Enter Postfix Expression");
gets(postfix);
char c;
while(*postfix!='\0')
{
c=*postfix;
if(is_operator(c)==2)
{
push((c-'0')); //Converting char to int before pushing it into the stack
}
if(is_operator(c)==1)
{
char op;
int n1,n2,n3;
op=*postfix;
n1=pop();
n2=pop();
switch(op)
{
case '+':
n3=n1+n2;
break;
case '-':
n3=n1-n2;
break;
case '*':
n3=n1*n2;
break;
case '/':
n3=n1/n2;
break;
}
push(n3);
}
postfix++;
}//end while
answer();
}
void push(int c)
{
top++;
stack[top]=c;
}
int pop()
{
int c;
c=stack[top];
top--;
return(c);
}
int is_operator(char i)
{
char ch=i;
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
{
return(1);
}
else
{
return(2);
}
}
void answer()
{
char ans;
ans=stack[top];
printf("Answere is %d",ans);
}
I hope it is helpful....
The problems I see with your code are: your switch() is missing break statements on the individual case clauses (and a default case might be nice too); when you push your non-operators (aka single digit numbers) on the stack, you push them as character codes rather then converting them to numbers so the math doesn't make sense; you're not properly handling the order of non-communitive operations like subtraction and division (use Unix dc command as a comparison tool); finally, don't reinvent booleans. Below is a rework of your code with the above changes and some style adjustments:
// Evaluate a postfix expression
#include <ctype.h>
#include <stdio.h>
#include <stdbool.h>
char stack[100];
int top = -1;
void push(char);
char pop(void);
bool is_operator(char);
void answer(void);
void push(char c)
{
stack[++top] = c;
}
char pop()
{
return stack[top--];
}
bool is_operator(char op)
{
return (op == '+' || op == '-' || op == '*' || op == '/');
}
void answer()
{
printf("Answer is %d\n", stack[top]);
}
int main()
{
char item, postfix[100];
int i = 0;
printf("Enter Postfix Expression: ");
gets(postfix);
while ((item = postfix[i++]) != '\0')
{
if (is_operator(item))
{
char n1 = pop();
char n2 = pop();
char n3 = 0;
switch (item)
{
case '+':
n3 = n1 + n2;
break;
case '-':
n3 = n2 - n1;
break;
case '*':
n3 = n1 * n2;
break;
case '/':
n3 = n2 / n1;
break;
}
push(n3);
} else if (isdigit(item)) {
push(item - '0');
}
} // end while
answer();
return 0;
}
Example (note this evaluator only operates on single digit numbers):
> ./a.out
Enter Postfix Expression: 6 4 - 7 * 1 +
Answer is 15
> dc
6 4 - 7 * 1 + p
15