Please I wrote this code to convert an expression to postfix, using the values of each row of an array. The expression can only be written using the words red, blue and green, which refer to col 1, col 2, col 3, respectively. Eg If I enter red*blue+green, I want to get the postfix of the values for row 1 and row 2 with respect to the entered expression. The code works but it stops after executing the first row. Please can someone find out what I could be missing or what I should do?
Code:#include<stdio.h>
#include<stdlib.h>
#include<string.h>
float values[2][3] = {{22.2,5.2,34},{3.93,43.3,15}};
char stack[200];
int stackSize = 0;
// stack implementation
void push( char ch ) { stack[stackSize++] = ch; }
char pop() { return (stackSize > 0) ? stack[--stackSize] : 0; }
char top() { return (stackSize > 0) ? stack[stackSize-1] : 0; }
int empty() { return stackSize == 0; }
int isOperator( char ch ) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
int priority(char ch)
{
if ( ch == '*' || ch == '/' || ch == '%' )
return 1;
else if ( ch == '+' || ch == '-' )
return 0;
else
return -1;
}
float getValue(int row, char * s )
{
if (strcmp(s, "red") == 0) return values[row][0];
if (strcmp(s, "green") == 0) return values[row][1];
if (strcmp(s, "blue") == 0) return values[row][2];
return 0;
}
int main( )
{
int pos,i;
char input[500];
pos=0;
printf ( "\nEnter an infix expression using red, blue and green: " ) ;
while ((input[pos++]=getchar()) != '\n');
input[--pos] ='\0';
char *s = input;
char buffer[500];
int bufferLen = 0;
char ch;
for(i=0; i<2; i++){
printf("Row %d is: ", i);
do
{
ch = s[0]; s++; // get next character
if (ch >= 'a' && ch <= 'z') {
// build string
buffer[bufferLen++] = ch;
} else
{
if ( bufferLen > 0 )
{
// string is complete, find its value
buffer[bufferLen] = 0;
printf("%g ", getValue(i,buffer));
bufferLen = 0;
}
if (isOperator(ch))
{
// infix to postfix conversion
while ( (!empty()) && (priority(top()) >= priority(ch)) )
{
printf("%c", pop() );
}
push( ch );
}
}
} while (ch > 0);
while (!empty())
{
printf("%c", pop() );
}
printf("\n\n");
}
}