Parsing an Expression in the form <id> = <expr> - parsing

When the program runs it asks me to write an expression to be parsed but when I type anything, I get this:
Enter an expression to be parsed below:
read * 3
Call lex...read
Enter <program>
Enter <statement>
Call lex...
ERROR: Must be of the form <id> = <expr>.
Here is the program:
#include <iostream>
#include <stdlib.h>
#include <cctype>
using namespace std;
int charClass;
char lexeme[100];
char nextChar;
int lexemeLength;
int token;
int nextmaiToken;
int i = 0;
string input;
int lex ();
void program ();
void statement ();
void expr ();
void term ();
void factor ();
#define LETTER 0
#define NUMBER 1
#define UNKNOWN 99
#define INT_CONSTANT 10
#define ID 11
#define ASSIGNMENT_OP 20
#define ADD_OP 21
#define SUB_OP 22
#define MULT_OP 23
#define DIV_OP 24
#define LEFT_PAREN 25
#define RIGHT_PAREN 26
#define EQUALS 27
#define END -1
void
addChar ()
{
if (lexemeLength <= 98)
{
lexeme[lexemeLength++] = nextChar;
lexeme[lexemeLength] = 0;
}
else
{
cout << "Error - lexeme is too long!\n\n";
exit (1);
}
}
void
getChar ()
{
nextChar = input[i++];
if (nextChar != END)
{
if (isalpha (nextChar))
charClass = LETTER;
else if (isdigit (nextChar))
charClass = NUMBER;
else
charClass = UNKNOWN;
}
else
charClass = END;
}
void
getNonBlank ()
{
if (isspace (nextChar))
getChar ();
}
int lookup (char ch)
{
switch (ch)
{
case '(':
addChar ();
nextmaiToken = LEFT_PAREN;
break;
case ')':
addChar ();
nextmaiToken = RIGHT_PAREN;
break;
case '+':
addChar ();
nextmaiToken = ADD_OP;
break;
case '-':
addChar ();
nextmaiToken = SUB_OP;
break;
case '*':
addChar ();
nextmaiToken = MULT_OP;
break;
case '/':
addChar ();
nextmaiToken = DIV_OP;
break;
case ';':
addChar ();
nextmaiToken = END;
break;
case '=':
addChar ();
nextmaiToken = EQUALS;
break;
default:
addChar ();
break;
}
return nextmaiToken;
}
int lex ()
{
lexemeLength = 0;
switch (charClass)
{
case LETTER:
addChar ();
getChar ();
while (charClass == LETTER || charClass == NUMBER)
{
addChar ();
getChar ();
}
nextmaiToken = ID;
break;
case NUMBER:
addChar ();
getChar ();
while (charClass == NUMBER)
{
addChar ();
getChar ();
}
nextmaiToken = INT_CONSTANT;
break;
case UNKNOWN:
lookup (nextChar);
getChar ();
break;
default:
nextmaiToken = END;
lexeme[0] = 'E';
lexeme[1] = 'O';
lexeme[2] = 'F';
break;
}
cout << "Call lex..." << lexeme << "\n";
return nextmaiToken;
}
void program ()
{
cout << "Enter <program>\n";
statement ();
if (nextmaiToken != END)
{
cout << "ERROR: No ending ';'\n\n";
exit (1);
}
else
{
cout << "Exit <program>\n";
cout << "This is a valid program.\n\n";
}
}
void statement ()
{
cout << "Enter <statement>\n";
if (nextmaiToken == ID)
{
lex ();
if (nextmaiToken == EQUALS)
{
lex ();
expr ();
}
else
{
cout << "ERROR: Must be of the form <id> = <expr>.\n\n";
exit (1);
}
}
else
{
cout << "ERROR: Must be of the form <id> = <expr>.\n\n";
exit (1);
}
cout << "Exit <statement>\n";
}
void expr ()
{
cout << "Enter <expr>\n";
term ();
while (nextmaiToken == ADD_OP || nextmaiToken == SUB_OP)
{
lex ();
term ();
}
cout << "Exit <expr>\n";
}
void term ()
{
cout << "Enter <term>\n";
factor ();
while (nextmaiToken == MULT_OP || nextmaiToken == DIV_OP)
{
lex ();
factor ();
}
cout << "Exit <term>\n";
}
void factor ()
{
cout << "Enter <factor>\n";
if (nextmaiToken == ID || nextmaiToken == INT_CONSTANT) //for the cases: <factor> -> id and <factor> -> int_constant
lex ();
else
{
if (nextmaiToken == LEFT_PAREN) //for the case: <factor> -> ( <expr> )
{
lex ();
expr ();
if (nextmaiToken == RIGHT_PAREN) //must close parentheses
lex ();
else
{
cout << "ERROR: No closing parentheses.\n\n";
exit (1);
}
}
else
{
cout << "ERROR: Unbalanced expression.\n\n";
exit (1);
}
}
cout << "Exit <factor>\n";
}
int main ()
{
cout << "\nEnter an expression:\n";
cin >> input;
cout << "\n";
nextChar = input[i];
getChar ();
lex ();
program ();
return (1);
}
The possible set of tokens, represented with regular expressions, includes:
= + - * / ( )
ID -> letter(letter|digit)*
Except read, write, and halt.
LETTER ->[a-zA-Z]
DIGIT ->[0-9]
What is missing or what is making stop early!!

Related

Why I am getting TLE at CSES problem "Book Shop" of dynamic programming

TLE
I am getting the same error in case of coin combination 2
link to the problem
Failed tc
//*******************************************
// Code by:
// * *
// * * * *
// ***** *****
// * * * *
// * *arushi * * garwal
//*******************************************
#include <bits/stdc++.h>
using namespace std;
#define fastio() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL);
#define yes cout << "YES\n"
#define no cout << "NO\n"
#define MOD 1000000007
#define endl "\n"
#define MOD1 998244353
#define INF 1e18
#define nline "\n"
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define for0 for (i = 0; i < n; i++)
#define for1 for (i = 1; i <= n; i++)
#define forr for (i = n - 1; i >= 0; i--)
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
// typedef tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update > pbds; // find_by_order, order_of_key
#ifndef ONLINE_JUDGE
#define debug(x) \
cerr << #x << " "; \
_print(x); \
cerr << endl;
#else
#define debug(x)
#endif
void _print(ll t)
{
cerr << t;
}
void _print(int t) { cerr << t; }
void _print(string t) { cerr << t; }
void _print(char t) { cerr << t; }
void _print(lld t) { cerr << t; }
void _print(double t) { cerr << t; }
void _print(ull t) { cerr << t; }
template <class T, class V>
void _print(pair<T, V> p);
template <class T>
void _print(vector<T> v);
template <class T>
void _print(set<T> v);
template <class T, class V>
void _print(map<T, V> v);
template <class T>
void _print(multiset<T> v);
template <class T, class V>
void _print(pair<T, V> p)
{
cerr << "{";
_print(p.ff);
cerr << ",";
_print(p.ss);
cerr << "}";
}
template <class T>
void _print(vector<T> v)
{
cerr << "[ ";
for (T i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T>
void _print(set<T> v)
{
cerr << "[ ";
for (T i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T>
void _print(multiset<T> v)
{
cerr << "[ ";
for (T i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T, class V>
void _print(map<T, V> v)
{
cerr << "[ ";
for (auto i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
// EVERY SINGLE QUES TAKES YOU TOWARDS YOUR GOAL :)
// ********************************************************
int i, t, j, sum, n, ans, k;
const int M = 1e9 + 7;
const int N = 1e5;
int dp[1001][N + 1];
ll binExp(ll a, ll b)
{
ll result = 1;
while (b > 0)
{
if (b & 1)
result = (result * a) % M;
a = (a * a) % M;
b >>= 1;
}
return result;
}
int fun(int i, int price[], int pages[], int cost)
{
if (i < 0)
return 0;
if (cost == 0)
return 0;
if (dp[i][cost] != -1)
return dp[i][cost];
int ans = fun(i - 1, price, pages, cost);
if (cost >= price[i])
ans = max(ans, fun(i - 1, price, pages, cost - price[i]) + pages[i]);
return dp[i][cost] = ans;
}
void hacked()
{
// cin>>n;
// string s;
// cin>>s;
cin >> n >> sum;
int price[n];
int pages[n];
memset(dp, -1, sizeof(dp));
for (i = 0; i < n; i++)
{
cin >> price[i];
}
for (i = 0; i < n; i++)
{
cin >> pages[i];
}
cout << fun(n - 1, price, pages, sum) << endl;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("Error.txt", "w", stderr);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
hacked();
return 0;
}`
I tried using int instead of long long but still getting tle.
You are in a book shop which sells n different books. You know the
price and number of pages of each book.
You have decided that the total price of your purchases will be at
most x. What is the maximum number of pages you can buy? You can buy
each book at most once.
Maybe because of the auxiliary space used up by top-down approach - the recursive stack- bottom-up works tho.
UPD: I just read this CF BLOG, people mention about the strict constraints of CSES, so it's better to solve using bottom-up.

Memory Leak in Binary Tree Initialize Function

I am attempting to make and evaluate a binary expression tree based on a postfix user input string in C. My binary tree initialization function is causing memory leaks, however. To summarize my algorithm, the user enters a postfix string of input which is parsed through by a function and assembled into the tree. Here's my full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
// Define binary expression tree data structure
typedef struct binExpTree {
char *val;
struct binExpTree *left;
struct binExpTree *right;
} expTree;
// Define expression tree stack data structure
typedef struct expTreeStack {
int height;
int used;
expTree **expTreeDarr;
} treeStack;
// Function prototypes
void initStack(treeStack *stack);
expTree * getTopStack(treeStack *stack);
int isEmptyStack(treeStack *stack);
void pushStack(treeStack *stack, expTree *treeNode);
expTree * popStack(treeStack *stack);
void clearStack(treeStack *stack);
expTree * initTree(char *val);
void printCommands();
expTree * parseExpression(char *expString);
void clearTree(expTree *rootNode);
void printInfix(expTree *rootNode);
void printPrefix(expTree *rootNode);
int evalExpression(expTree *rootNode);
/* File contains all functions necessary for stack operations */
// Initialize empty binary tree stack of size 4
void initStack(treeStack *stack) {
stack->height = 4;
stack->used = 0;
stack->expTreeDarr = (expTree **)malloc(sizeof(expTree *) * stack->height);
}
// Return the tree node from the stack's top
expTree * getTopStack(treeStack *stack) {
if (stack->used > 0) {
return stack->expTreeDarr[stack->used - 1];
}
else {
return NULL;
}
}
// Discern whether tree stack is empty
int isEmptyStack(treeStack *stack) {
if (stack->used == 0) {
return TRUE;
}
else {
return FALSE;
}
}
// Push tree node pointer onto stack
void pushStack(treeStack *stack, expTree *treeNode) {
if (stack->used == stack->height) {
expTree **expTreeTmp = stack->expTreeDarr;
stack->height += 4;
stack->expTreeDarr = (expTree **)malloc(sizeof(expTree *) * stack->height);
for (int i = 0; i < stack->used; i++) {
stack->expTreeDarr[i] = expTreeTmp[i];
//free(expTreeTmp[i]);
}
free(expTreeTmp);
}
stack->expTreeDarr[stack->used] = treeNode;
stack->used = stack->used + 1;
}
// Pop tree node pointer from the stack
expTree * popStack(treeStack *stack) {
expTree *stackTmp = getTopStack(stack);
expTree *newNode = (expTree *)malloc(sizeof(expTree));
*newNode = *stackTmp;
stack->used -= 1;
return newNode;
}
// Empty stack of all data (make sure this works)
void clearStack(treeStack *stack) {
for (int i = 0; i < stack->used; i++) {
clearTree(stack->expTreeDarr[i]);
}
free(stack->expTreeDarr);
stack->used = 0;
stack->height = 0;
}
/* File contains all functions necessary for binary tree operations */
// Initialize binary expression tree with specified operator/operand
expTree * initTree(char *val) {
expTree *newTree = (expTree *)malloc(sizeof(expTree));
newTree->val = (char *)malloc(strlen(val) + 1);
strcpy(newTree->val, val);
newTree->left = NULL;
newTree->right = NULL;
return newTree;
}
// Print commands available to the user
void printCommands() {
printf("The commands for this program are:\n\n");
printf("q - to quit the program\n");
printf("? - to list the accepted commands\n");
printf("or any postfix mathematical expression using the operators of *, /, +, -\n");
}
// Return size of binary expression tree
int sizeTree(expTree *treeNode) {
if (treeNode == NULL) {
return 0;
}
else {
return 1 + sizeTree(treeNode->left) + sizeTree(treeNode->right);
}
}
// Construct a postfix binary expression tree from expression string
expTree * parseExpression(char *expString) {
char *expStringCopy = (char *)malloc(strlen(expString) + 1);
expTree *treeNode;
treeStack expStack;
initStack(&expStack);
strcpy(expStringCopy, expString);
char *expStringTok = strtok(expStringCopy, " ");
while (expStringTok != NULL) {
if (*expStringTok == '+' || *expStringTok == '-' ||
*expStringTok == '*' || *expStringTok == '/') {
if (expStack.used < 2) {
return NULL;
}
treeNode = initTree(expStringTok);
treeNode->right = popStack(&expStack);
treeNode->left = popStack(&expStack);
pushStack(&expStack, treeNode);
}
else {
treeNode = initTree(expStringTok);
pushStack(&expStack, treeNode);
}
expStringTok = strtok(NULL, " ");
}
if (expStack.used > 1 || (*(treeNode->val) != '+' && *(treeNode->val) != '-' &&
*(treeNode->val) != '*' && *(treeNode->val) != '/')) {
return NULL;
}
free(expStringCopy);
treeNode = popStack(&expStack);
clearStack(&expStack);
return treeNode;
}
// Clear binary expression tree
void clearTree(expTree *rootNode) {
if (rootNode == NULL) {
return;
}
else {
clearTree(rootNode->left);
clearTree(rootNode->right);
free(rootNode->val);
free(rootNode);
}
}
// Print infix notation of expression
void printInfix(expTree *rootNode) {
if (rootNode == NULL) {
return;
}
else {
if (*(rootNode->val) == '+' || *(rootNode->val) == '-' ||
*(rootNode->val) == '*' || *(rootNode->val) == '/') {
printf("( ");
}
printInfix(rootNode->left);
printf(" %s ", rootNode->val);
printInfix(rootNode->right);
if (*(rootNode->val) == '+' || *(rootNode->val) == '-' ||
*(rootNode->val) == '*' || *(rootNode->val) == '/') {
printf(" )");
}
}
}
// Print prefix notation of expression
void printPrefix(expTree *rootNode) {
if (rootNode == NULL) {
return;
}
else {
printf(" %s ", rootNode->val);
printPrefix(rootNode->left);
printPrefix(rootNode->right);
}
}
// Evaluate the expression tree
int evalExpression(expTree *rootNode) {
char op;
if (*(rootNode->val) == '+') {
return evalExpression(rootNode->left) + evalExpression(rootNode->right);
}
else if (*(rootNode->val) == '-') {
return evalExpression(rootNode->left) - evalExpression(rootNode->right);
}
else if (*(rootNode->val) == '*') {
return evalExpression(rootNode->left) * evalExpression(rootNode->right);
}
else if (*(rootNode->val) == '/') {
return evalExpression(rootNode->left) / evalExpression(rootNode->right);
}
else {
return atoi(rootNode->val);
}
}
int main(int argc, char const *argv[])
{
char input[300];
expTree *expPostfix;
/* set up an infinite loop */
while (1)
{
fgets(input,300,stdin);
/* remove the newline character from the input */
int i = 0;
while (input[i] != '\n' && input[i] != '\0') {
i++;
}
input[i] = '\0';
/* check if user enter q or Q to quit program */
if ( (strcmp (input, "q") == 0) || (strcmp (input, "Q") == 0) )
break;
/* check if user enter ? to see command list */
else if ( strcmp (input, "?") == 0)
printCommands();
/* user enters an expression */
else {
// Parse the expression into a binary expression tree
printf("%s\n", input);
expPostfix = parseExpression(input);
// Discern whether expression is valid
if (expPostfix == NULL) {
printf("Invalid expression. Enter a valid postfix expression \n");
continue;
}
// Print the expression in infix notation
printf("Infix notation: ");
printInfix(expPostfix);
printf("\n");
// Print the expression in prefix notation
printf("Prefix notation: ");
printPrefix(expPostfix);
printf("\n");
// Print the expression in postfix notation
printf("Postfix notation: ");
printf("%s\n", input);
// Evaluate expression and print result
printf("Expression result: %d \n\n", evalExpression(expPostfix));
clearTree(expPostfix);
}
}
printf("\nGoodbye\n");
return 0;
}
Upon running with Valgrind and an input of "1 1 -", this is the output:
==35604==
==35604== HEAP SUMMARY:
==35604== in use at exit: 72 bytes in 3 blocks
==35604== total heap usage: 13 allocs, 10 frees, 2,236 bytes allocated
==35604==
==35604== 24 bytes in 1 blocks are definitely lost in loss record 1 of 2
==35604== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==35604== by 0x10952C: initTree (proj4base_38.c:143)
==35604== by 0x1096CC: parseExpression (proj4base_38.c:194)
==35604== by 0x109B8A: main (proj4base_38.c:323)
==35604==
==35604== 48 bytes in 2 blocks are definitely lost in loss record 2 of 2
==35604== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==35604== by 0x10952C: initTree (proj4base_38.c:143)
==35604== by 0x109719: parseExpression (proj4base_38.c:201)
==35604== by 0x109B8A: main (proj4base_38.c:323)
==35604==
==35604== LEAK SUMMARY:
==35604== definitely lost: 72 bytes in 3 blocks
==35604== indirectly lost: 0 bytes in 0 blocks
==35604== possibly lost: 0 bytes in 0 blocks
==35604== still reachable: 0 bytes in 0 blocks
==35604== suppressed: 0 bytes in 0 blocks
==35604==
==35604== For lists of detected and suppressed errors, rerun with: -s
==35604== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
So it seems the culprit is my initTree() function. However, I just cannot wrap my head around why this memory is being lost. I hope this isn't too much code. This is an edit from previously, where someone informed me there was not enough information to go on.
The leak is caused by popStack, because the target of stackTmp gets leaked when the function exits:
expTree * popStack(treeStack *stack) {
expTree *stackTmp = getTopStack(stack);
expTree *newNode = (expTree *)malloc(sizeof(expTree));
*newNode = *stackTmp;
stack->used -= 1;
return newNode;
}
Given that the stack seemed to be the exclusive owner of the tree, and it no longer has a pointer to it, popStack can avoid the leak by simply not making a copy and returning the original:
expTree * popStack(treeStack *stack) {
expTree *topNode = getTopStack(stack);
stack->used -= 1;
return topNode;
}

reading doubly linked list n position

My doubly linked list contains abc...z. which was read from first file..
My second file contains int 4,10,8,-3.
based on my second file I am suppose do display abc..z on the screen..
4 -> I am going forward till D then 10 -> more till N, then so on..
How can I do that? please any help..
anyhlep would be really appriciated..
#include <iostream>
#include <fstream>
using namespace std;
class Myclass{
public:
void putItem(char cha);
void printItme();
void getIndex(int);
Myclass();
private:
struct Node
{
char aplBat;
Node *next;
Node *prev;
};
Node *head;
int potionIndex = 0;
};
int main(){
ifstream inputFile, inputInt;
Myclass obj;
string stringInt;
double valData = 0;
int total = 0;
char charData;
/*my first file with alpa */
inputFile.open("Letters.txt");
if(inputFile.good())
{
while(inputFile >> charData)
{
obj.putItem(charData);
}
}
else
cout << "Error " << endl;
inputFile.close();
//From right here.. I am reading data from file Sequence, 3,5,-2,10,-5
inputInt.open("Sequence.txt");
if(inputInt.good())
{
while(getline(inputInt, stringInt, ',')){
valData = atof(stringInt.c_str());
total += valData;
obj.getIndex(total);
}
//cout << "Total " << total << endl;
cout << "FIle ok " << endl;
obj.printItme();
}
else
cout << "Error " << endl;
inputInt.close();
cout << endl;
return 0;
}
void Myclass::putItem(char cha){
Node *newNode;
newNode = new Node;
newNode->aplBat = cha;
newNode->prev = nullptr;
newNode->next = nullptr;
if(!head)
{
head = newNode;
}
else
{
head->prev = newNode;
newNode->next = head;
head = newNode;
}
}
void Myclass::printItme()
{
Node *temp = head;
if(temp == nullptr)
{
cout << "Empty List " << endl;
}
while(temp->next != nullptr)
{
temp = temp->next;
}
while(temp->prev != nullptr)
{
cout << temp->aplBat << " ";
temp = temp->prev;
}
cout << "Repitation " << potionIndex << endl;
}
Myclass::Myclass()
{
head = nullptr;
}
void Myclass::getIndex(int val)
{
potionIndex = val;
}

(HW) Pallindrom using Stack and Queue, Run Time Error

Alright, i have a hw assignment to check if an inserted string is a palindrome. The string must first be inserted into a stack, a queue, and then compared. I have the program up and running, for me that is. My teacher, when trying to grade it experience(d) a run time error. Also, getline portable is a requirement of the assignment and came with the file and instructions.
This is the note from the teacher:
Check if a line is a palindrome. Ignore spaces? y/n y (her running the code)
Input line to check
(where she gets the runtime error)
175 [main] csc240Summer2014PE8Student 10060 open_stackdumpfile: Dumping stack trace to csc240Summer2014PE8Student.exe.stackdump
#include <iostream>
#include <stack>
#include <queue>
#include <string>
using namespace std;
istream& getline_portable( istream& is, string& str ) {
istream& ris = std::getline(is,str);
if ( str.size() && str[str.size()-1] == '\r' )
str.resize(str.size()-1);
return ris;
}
int main()
{
stack<char> s;
queue<char> q;
char c, choice, b;
string str;
int i = 0;
int count = 0;
do
{
cout<<"Check if a line is a palindrome. Ignore spaces? y/n ";
cin >> b;
cin.ignore();
tolower(b);
cout<<"Input line to check\n";
getline_portable(cin,str);
for(int j = 0; j < str.size(); j++)
str[j] = tolower(str[j]);
if(b == 'n')
{
for(int j = 0; j < str.size(); j++)
{
c = str[j];
q.push(c);
s.push(c);
}
}
else if (b == 'y')
{
for(int j = 0; j < str.size() - count; j++)
{
c = str[j];
if(isspace(c))
{
}
else if(!isspace(c))
{
q.push(c);
s.push(c);
}
}
}
do
{
if(q.front() != s.top())
{
i = false;
break;
}
else
{
i = true;
s.pop();
q.pop();
}
}while(!q.empty() && !s.empty());
if (i == true)
cout << str << " is a pallindrom.\n";
else if (i == false)
cout << "Your input of " << str << " is not a pallindrome.\n";
cout << "Would you like to test another string? y/n ";
cin >> choice;
tolower(choice);
cin.ignore();
}while (choice == 'y');
cout << "Press enter to continue...";
cin.get();
return 0;
}

Is there a way to get my program to convert characters to integers?

I have been running this and typing "12+" as the expression. 'm down to trying to add the top value and next value and it keeps giving me the result 'c' but I want the result to be 3. So is there any way to get my program to convert char 'c' to int '3' and char 'd' to int 4 and so on ?
//array based stack implementation
class Stack
{
private:
int capacity; //max size of stack
int top; //index for top element
char *listArray; //array holding stack elements
public:
Stack (int size = 50){ //constructor
capacity = size;
top = 0;
listArray = new char[size];
}
~Stack() { delete [] listArray; } //destructor
void push(char it) { //Put "it" on stack
listArray[top++] = it;
}
char pop() { //pop top element
return listArray [--top];
}
char& topValue() const { //return top element
return listArray[top-1];
}
char& nextValue() const {//return second to top element
return listArray[top-2];
}
int length() const { return top; } //return length
};
int main()
{
string exp;
char it = ' ';
int count;
int push_length;
cout << "Enter an expression in postfix notation:\n";
cin >> exp;
cout << "The number of characters in your expression is " << exp.length() << ".\n";
Stack STK;
for(count= 0; count < exp.length() ;count++)
{
if (exp[count] == '+')
{
it = exp[count - 1];
cout << it << "?\n";
while (!isdigit(it))
{
cout << it << "!\n";
it = exp[count--];
}
STK.push(it);
cout << STK.topValue() << "\n";
it = exp[count - 2];
cout << it << "\n";
if (isdigit(it))
{
STK.push(it);
}
cout << STK.topValue() << "\n";
cout << STK.nextValue() << "\n";
it = STK.topValue() + STK.nextValue();
cout << it << "\n";
STK.pop();
STK.pop();
STK.push(it);
cout << STK.topValue() << "\n";
}
}
cout << "The number of characters pushed into the stack is " << STK.length() << ".\n";
push_length = STK.length();
return(0);
}
You could do something like this:
char ch='d'; //ch is the character to convert
int i=1+(ch-'a');

Resources