Hi Experts!
i need some help now i have written a code but my output is not correct its reading everything from text file but not computing it correctly,,,pls pls help.
here's my code....
#include <iostream>
#include <iomanip>
#include <stack>
#include <fstream>
#include <string>
using namespace std;
using std::string;
using std::cout;
using std::cerr;
#define MAX 20
//global variables
string vars=""; //add the variables to this string as you read them
int vals[26]; //add the values of the variables to this array as you read them
int valA;
int valB;
string pf[MAX];
int num_vars; //number of variables
int num_pfs;
int ndx;
stack<int>s;
int found;
int ops;
int lenops;
char token;
int i;
void process_pf(string pf);
int var2ndx(string var) { //given a variable it returns its index in vars
//so that its value may be found as vals[index]
ndx=vars.find(var);
if ( (ndx>=0) && (ndx<vars.length()) ) return ndx;
cout << "illegal variable " << var << "n";
return -1; //this signals that the variable is invalid
}
void read_vars_vals(){
string var; int val;
ifstream inf;
inf.open("c:temp575_prog2_data.txt");
if (!inf) { cout << "input data should be in c:temp575_prog2_data.txtn"; exit(0); }
//read the number of variables (global)
inf >> num_vars;
//loop and read this many vars and vals
for (int i=0; i<num_vars; i++) {
inf >> var >> val;
vars=vars+var;
vals=val;
cout<<vars<<" "<<vals<<endl;
}
//then read all the strings of postfx expressions into an array of strings
int i=0;
while (inf >> pf) i++; //pf is the array of postfix strings (global variable)
num_pfs=i;
inf.close();
}
bool is_operand(string ch) {
found=vars.find(ch); int lenvars=vars.length();
if ( (found>=0) && (found<lenvars) ) return true;
else return false;
}
bool is_operator(string ch) {
string ops="+-^*/"; found=ops.find(ch); lenops=ops.length();
if ( (found>=0) && (found<lenops) ) return true;
else return false;
}
void process_operand(string opnd,int i) {
if (is_operand(opnd))
s.push(vals);
else
cout<<"invalid postfix error" <<endl;
// process_pf(opnd);
}
void process_operator(string op) {
if (is_operator(op))
{
valA = s.top();
s.pop();
valB = s.top();
s.pop();
}
}
void process_pf(string pf) { //pf=a single postfix
// i=0;
token = pf;
//while((i < pf.size()) && (token != '='))
//{
switch(token)
{
case '+': vals = valA + valB;
break;
case '-': vals = valB - valA;
break;
case '*': vals = valA*valB;
break;
case '^':vals = valA^valB;
case '/':
try
{
vals = valA/valB;
}
catch(...)
{
cerr<<"divide by zero error";
}
break;
}
s.push(vals);
//i++;
//token = pf;
cout << pf << " " << vals << endl;
cout << endl;
}
void main() {
read_vars_vals();
for (i=0; i<num_pfs; i++) {
process_operand(pf,i);
process_operator(pf);
process_pf(pf);
}
//footer info like your name etci]
}