I'm trying to create a program that converts an arithmetic expression from infix to postfix form. As long as I don't call the "infixToPostFix" function, the program runs fine.
But when I try to run the following code, I get a crash and error "deque iterator not dereferenceable". I can't find any dereferencing operators, so I'm not sure what's wrong:
// infixToPostfixTest.cpp
#include "Token.h"
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
// infix to postfix function prototype
void infixToPostfix(vector<Token> &infix, vector<Token> &postfix);
// priority function prototype
int priority(Token & t);
// printing a Token vector
void printTokenVector(vector<Token> & tvec);
int main() {
// Experiment
//--------------------------------------------------
vector<Token> infix;
// a + b * c - d / e % f
//
infix.push_back(Token(VALUE,5.0)); // a
infix.push_back(Token(OPERATOR,'+'));
infix.push_back(Token(VALUE,6.0)); // b
infix.push_back(Token(OPERATOR,'*'));
infix.push_back(Token(VALUE,7.0)); // c
cout << "Infix expression: ";
printTokenVector(infix);
vector<Token> postfix; // create empty postfix vector
infixToPostfix(infix, postfix); // call inToPost to fill up postfix vector from infix vector
cout << "Postfix expression: ";
printTokenVector(postfix);
cout << endl << endl;
return 0;
}
// printing a Token vector
void printTokenVector(vector<Token> & tvec)
{
int size = tvec.size();
for (int i = 0; i < size; i++) {
cout << tvec[i] << " ";
}
cout << endl;
}
int priority(Token & t) // assumes t.ttype is OPERATOR, OPEN, CLOSE, or END
{
char c = t.getChar();
char tt = t.getType();
if (c == '*' || c == '/')
return 2;
else if (c == '+' || c == '-')
return 1;
else if (tt == OPEN)
return 0;
else if (tt == END)
return -1;
else
return -2;
}
void infixToPostfix(vector<Token> &infix, vector<Token> &postfix)
{
stack<Token> stack;
postfix.push_back(END);
int looper = 0;
int size = infix.size();
while(looper < size) {
Token token = infix[looper];
if (token.getType() == OPEN)
{
stack.push(token);
}
else if (token.getType() == CLOSE)
{
token = stack.top();
stack.pop();
while (token.getType() != OPEN)
{
postfix.push_back(token);
token = stack.top();
stack.pop();
}
}
else if (token.getType() == OPERATOR)
{
Token topToken = stack.top();
while ((!stack.empty()) && (priority(token) <= priority(topToken)))
{
Token tokenOut = stack.top();
stack.pop();
postfix.push_back(tokenOut);
topToken = stack.top();
}
stack.push(token);
}
else if (token.getType() == VALUE)
{
postfix.push_back(token);
}
else
{
cout << "Error! Invalid token type.";
}
looper = looper + 1;
}
while (!stack.empty())
{
Token token = stack.top();
stack.pop();
postfix.push_back(token);
}
}
//Token.h
#ifndef TOKEN_H
#define TOKEN_H
#include <iostream>
using namespace std;
enum TokenType { OPEN, CLOSE, OPERATOR, VARIABLE, VALUE, END };
class Token {
public:
Token (TokenType t, char c) : ttype(t), ch(c) { }
Token (TokenType t, double d) : ttype(t), number(d) { }
Token (TokenType t) : ttype(t) { }
Token () : ttype (END), ch('?'), number(-99999999) { }
TokenType getType() {return ttype;}
char getChar() {return ch;}
double getNumber() {return number;}
private:
TokenType ttype;
char ch;
double number;
};
ostream & operator << (ostream & os, Token & t) {
switch (t.getType()) {
case OPEN:
os << "("; break;
case CLOSE:
os << ")"; break;
case OPERATOR:
os << t.getChar(); break;
case VARIABLE:
os << t.getChar(); break;
case VALUE:
os << t.getNumber(); break;
case END:
os << "END" ; break;
default: os << "UNKNOWN";
}
return os;
}
stack is implemented using container, since stack is container adaptor, by default deque is used. In probably one line of your code - you call pop/top on empty stack, that is not allowed.
trace show, that error is after Token +.
Problem is here:
else if (token.getType() == OPERATOR)
{
Token topToken = stack.top();
You try to top from empty stack, since stack in case, where is only NUMBER token before OPERATOR token, is empty.
You are calling top on empty stack, just follow the code for your test.
you start with an empty stack
you encounter a VALUE, you don't change stack
you encounter an OPERATOR and attempt to access stack.top()
I ran into this problem too. I think the problem is in this sort of code:
else if (token.getType() == CLOSE)
{
token = stack.top();
stack.pop();
while (token.getType() != OPEN)
{
postfix.push_back(token);
token = stack.top();
stack.pop();
}
}
The problem is that 'token' is a reference to the top, not a copy. So you can't pop the stack until you are done working with token. In my case, it often still worked because the information was still present, but then it would crash at weird times. You need to organize this code in a different way to pop only after you done working with 'token'.
Maybe something like:
else if (token.getType() == CLOSE)
{
token = stack.top();
Token saveToken = new Token(token); // Or something like this...
stack.pop();
while (saveToken.getType() != OPEN)
{
postfix.push_back(saveToken);
token = stack.top();
delete saveToken; // ugh
Token saveToken = new Token(token);
stack.pop();
}
delete saveToken; //ugh
}
Related
So I have been solving problems from this book called
Programming: Principles and Practice Using C++ by Bjarne Stroustrup to learn C++ and have been enjoying it a lot. I recently got stuck on this question in Chapter 10 (Input and Output
Streams).
The question is given below:
Add a command from x to the calculator from Chapter 7 that makes it
take input from a file x. Add a command to y to the calculator that
makes it write its output (both standard output and error output) to
file y.
The source code for the above mentioned calculator is given below:
/*
Simple Calculator
This program implements a basic expression calculator.
Input from cin; output to cout.
The grammar for input is:
Calculation:
Statement
Print
Quit
Statement:
Declaration
Expression
Declaration:
"let" Name "=" Expression
Print:
;
Quit:
q
Expression:
Term
Term '+' Expression //addition
Term '-' Expression //subtraction
Term:
Primary
Term '*' Primary //multiplication
Term '/' Primary //division
Term '%' Primary //mod division
Primary:
Number
'(' Expression ')'
'-' Primary
'+' Primary
Number:
floating-point-literal
Input comes from cin through the Token_stream called ts.
*/
#include "../../std_lib_facilities.h"
class Token //a very simple user-defined type
{
public:
char kind = ' '; //what kind of token
double value = 0; //for numbers: a value
string name = " "; //for strings: a name
Token(char ch) :kind{ ch } { } //initialize kind with ch
Token(char ch, double val) :kind{ ch }, value{ val } {} //initializes kind and value
Token(char ch, string n) :kind{ ch }, name{ n } { } //initializes kind and name
};
class Token_stream
{
public:
//user interface
Token get(); //get a Token
void putback(Token t); //put a Token back
void ignore(char c); //discard characters up to and including a c
private:
//implementation details
//(not directly accessible to users of Token_stream)
bool full{ false }; //is there a Token in the buffer?
Token buffer = 0; //here is where we keep a Token put back with putback()
};
class Variable
{
public:
string name = " ";
string const_name = " ";
double value = 0;
};
vector<Variable>var_table;
double get_value(string s)
//return the value of the Variable named s
{
for (const Variable& v : var_table) {
if (v.name == s) return v.value;
if (v.const_name == s) return v.value;
}
error("get: undefined variable ", s);
return 1;
}
void set_value(string s, double d)
//set the Variable named s to d
{
for (Variable& v : var_table)
{
if (v.name == s)
{
v.value = d;
return;
}
if (v.const_name == s)
{
error("set: cannot assign a new value to an existing constant");
return;
}
}
error("set: undefined variable", s);
}
const char number = '8'; //t.kind == number means that t is a number Token
const char quit = 'q'; //t.kind == quit means that t is a quit Token
const char print = ';'; //t.kind == print means that t is a print token
const char name = 'a'; //name token
const char constant = 'c'; //constant token
const string constdeclkey = "const"; //constant keyword
const char let = 'L'; //declaration token
const string declkey = "let"; //declaration keyword
const string prompt = "> ";
const string result = "= "; //used to indicate that what follows is a result
void Token_stream::putback(Token t)
{
if (full) error("putback() into a full buffer");
buffer = t; //copy t to buffer
full = true; //buffer is now full
}
void Token_stream::ignore(char c)
//c represents the kind of Token
{
//first look in buffer:
if (full && c == buffer.kind)
{
full = false;
return;
}
full = false;
//now search input:
char ch = 0;
while (cin >> ch)
if (ch == c) return;
}
Token Token_stream::get()
{
if (full)
{
full = false; //do we already have a Token ready?
return buffer; //remove Token from buffer
}
char ch;
cin >> ch; //note that >> skips whitespace(space, newline, tab, etc)
switch (ch)
{
case ';': //for "print"
case 'q': //for "quit"
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
case '%':
case '=':
return Token{ ch }; //let each character represent itself
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
cin.putback(ch); //put digit back into the input stream
double val;
cin >> val; //read a floating-point number
return Token{ number, val }; //let '8' represent a "a number"
}
default:
if (isalpha(ch))
{
string s;
s += ch;
while (cin.get(ch) && (isalpha(ch) || isdigit(ch) || ch == '_')) s += ch;
cin.putback(ch);
if (s == declkey) return Token(let); //declaration keyword
else if (s == constdeclkey) return Token(constant);
return Token{ name, s };
}
error("Bad Token");
return 1;
}
}
bool is_declared(string var)
//is var already in var_table?
{
for (const Variable& v : var_table)
{
if (v.name == var) return true;
}
for (const Variable& v : var_table)
{
if (v.const_name == var) return true;
}
return false;
}
double define_name(string var, double val)
//add (var, val) to var_table
{
if (is_declared(var)) set_value(var, val);
Variable v;
v.name = var;
v.value = val;
var_table.push_back(v);
return val;
}
double define_const_name(const string constant, double val)
//add (constant, val) to var_table
{
if (is_declared(constant)) error(constant, " constant declared twice");
Variable v;
v.const_name = constant;
v.value = val;
var_table.push_back(v);
return val;
}
Token_stream ts; //makes a Token_stream called ts that reads from cin
double expression(); //declaration so that primary() can call it
double declaration()
//assume we have seen "let"
//handle: name = expression
//declare a variable called "name" with the initial value "expression"
{
Token t = ts.get();
if (t.kind != name) error("name expected in declaration");
string var_name = t.name;
Token t2 = ts.get();
if (t2.kind != '=') error("= missing in declaration of ", var_name);
double d = expression();
define_name(var_name, d);
return d;
}
double const_declaration()
//assume we have seen "const"
//handle: const_name = expression
//declare a constant called "const" with the initial value "expression"
{
Token t = ts.get();
if (t.kind != name) error("constant_name expected in declaration");
const string const_name = t.name;
Token t2 = ts.get();
if (t2.kind != '=') error("= missing in declaration of ", const_name);
double d = expression();
define_const_name(const_name, d);
return d;
}
double primary()
//deals with numbers and parantheses
//calls expression() and get_token()
{
Token t = ts.get();
switch (t.kind)
{
case '(': //handle '(' expression ')'
{
double d = expression();
t = ts.get();
if (t.kind != ')') error("')' expected");
return d;
}
case number: //we use '8' to represent a number
return t.value; //return the number's value
case '-':
return -primary();
case '+':
return primary();
case name:
return get_value(t.name);
default:
error("primary expected");
return 1;
}
}
double term()
//deals with * and -
//calls primary and get_token()
{
double left = primary(); //read and evaluate a Primary
Token t = ts.get(); //get the next token
while (true)
{
switch (t.kind) //see which kind of token it is
{
case '*':
left *= primary(); //evaluate Primary and multiply
t = ts.get();
break;
case '/':
{
double d = primary(); //evaluate Primary and divide
if (d == 0) error("divide by zero"); //check if primary isnt zero
left /= d;
t = ts.get();
break;
}
case '%':
{
double d = primary();
if (d == 0) error("divide by zero");
left = fmod(left, d);
t = ts.get();
break;
}
default:
ts.putback(t); //put t back into Token stream
return left; //return result to Expression
}
}
}
double expression()
//deals with + and -
//calls term() and get_token()
{
double left = term(); //read and evaluate an Term
Token t = ts.get(); //get the next token from the Token stream
while (true)
{
switch (t.kind) //see which kind of token it is
{
case '+':
left += term(); //evaluate Term and add
t = ts.get();
break;
case '-':
left -= term(); //evaluate Term and subtract
t = ts.get();
break;
default:
ts.putback(t); //put t back into the token stream
return left; //return the answer
}
}
}
void clean_up_mess() //B)
{
//skip until we find a print
ts.ignore(print);
}
double statement()
{
Token t = ts.get();
switch (t.kind)
{
case let:
return declaration();
case constant:
return const_declaration();
default:
ts.putback(t);
return expression();
}
}
void calculate() //expression evaluation loop
{
double val = 0;
while (cin)
try
{
cout << prompt; //print prompt
Token t = ts.get();
while (t.kind == print) //';' for "print now"
t = ts.get(); //eat ';'
if (t.kind == quit) //'q' for "quit"
{
return;
}
ts.putback(t);
cout << result << statement() << '\n';
}
catch (exception& e)
{
cerr << e.what() << '\n'; //write error message
clean_up_mess();
}
}
int main() //main loop and deals with errors
{
try
{
//predefined names:
define_const_name("pi", 3.1415926535);
define_const_name("e", 2.7182818284);
calculate();
keep_window_open();
return 0;
}
catch (exception& e)
{
cerr << e.what() << '\n';
keep_window_open("~~");
return 1;
}
catch (...)
{
cerr << "exception \n";
keep_window_open();
return 2;
}
}
The calculator kind of works like this:
> (2+3)-4*(5/6); //Input
= 1.66667 //Output
> //Next Input
It can also declare variables and constants and then use them back into for calculations:
> let x = 2; //Variable 1
= 2 //assigned value for Var 1
> const y = 3; //Constant 1
= 3 //assigned value Const 1
> x + y; //added var 1 to const 1
= 5 //result
> //next input
Also ; acts like a print character. The expression gets evaluated and displayed as soon as it reads ; and then it clears the token stream and gets ready to read the next input.
The custom header file std.lib.facilities.h is a collection of most standard C++ libraries and functions some of which are written by Bjarne Stroustrup and might have been used in the code given above.
I have also left the code for that header file just in case if someone is curious:
/*
std_lib_facilities.h
*/
/*
simple "Programming: Principles and Practice using C++ (second edition)" course header to
be used for the first few weeks.
It provides the most common standard headers (in the global namespace)
and minimal exception/error support.
Students: please don't try to understand the details of headers just yet.
All will be explained. This header is primarily used so that you don't have
to understand every concept all at once.
By Chapter 10, you don't need this file and after Chapter 21, you'll understand it
Revised April 25, 2010: simple_error() added
Revised November 25 2013: remove support for pre-C++11 compilers, use C++11: <chrono>
Revised November 28 2013: add a few container algorithms
Revised June 8 2014: added #ifndef to workaround Microsoft C++11 weakness
Revised Febrary 2 2015: randint() can now be seeded (see exercise 5.13).
Revised August 3, 2020: a cleanup removing support for ancient compilers
*/
#ifndef H112
#define H112 080315L
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
//------------------------------------------------------------------------------
typedef long Unicode;
//------------------------------------------------------------------------------
using namespace std;
template<class T> string to_string(const T& t)
{
ostringstream os;
os << t;
return os.str();
}
struct Range_error : out_of_range { // enhanced vector range error reporting
int index;
Range_error(int i) :out_of_range("Range error: " + to_string(i)), index(i) { }
};
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
using size_type = typename std::vector<T>::size_type;
/* #ifdef _MSC_VER
// microsoft doesn't yet support C++11 inheriting constructors
Vector() { }
explicit Vector(size_type n) :std::vector<T>(n) {}
Vector(size_type n, const T& v) :std::vector<T>(n, v) {}
template <class I>
Vector(I first, I last) : std::vector<T>(first, last) {}
Vector(initializer_list<T> list) : std::vector<T>(list) {}
*/
using std::vector<T>::vector; // inheriting constructor
T& operator[](unsigned int i) // rather than return at(i);
{
if (i<0 || this->size() <= i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
const T& operator[](unsigned int i) const
{
if (i<0 || this->size() <= i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
};
// disgusting macro hack to get a range checked vector:
#define vector Vector
// trivially range-checked string (no iterator checking):
struct String : std::string {
using size_type = std::string::size_type;
// using string::string;
char& operator[](unsigned int i) // rather than return at(i);
{
if (i<0 || size() <= i) throw Range_error(i);
return std::string::operator[](i);
}
const char& operator[](unsigned int i) const
{
if (i<0 || size() <= i) throw Range_error(i);
return std::string::operator[](i);
}
};
namespace std {
template<> struct hash<String>
{
size_t operator()(const String& s) const
{
return hash<std::string>()(s);
}
};
} // of namespace std
struct Exit : runtime_error {
Exit() : runtime_error("Exit") {}
};
// error() simply disguises throws:
inline void error(const string& s)
{
throw runtime_error(s);
}
inline void error(const string& s, const string& s2)
{
error(s + s2);
}
inline void error(const string& s, int i)
{
ostringstream os;
os << s << ": " << i;
error(os.str());
}
template<class T> char* as_bytes(T& i) // needed for binary I/O
{
void* addr = &i; // get the address of the first byte
// of memory used to store the object
return static_cast<char*>(addr); // treat that memory as bytes
}
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
inline void keep_window_open(string s)
{
if (s == "") return;
cin.clear();
cin.ignore(120, '\n');
for (;;) {
cout << "Please enter " << s << " to exit\n";
string ss;
while (cin >> ss && ss != s)
cout << "Please enter " << s << " to exit\n";
return;
}
}
// error function to be used (only) until error() is introduced in Chapter 5:
inline void simple_error(string s) // write ``error: s and exit program
{
cerr << "error: " << s << '\n';
keep_window_open(); // for some Windows environments
exit(1);
}
// make std::min() and std::max() accessible on systems with antisocial macros:
#undef min
#undef max
// run-time checked narrowing cast (type conversion). See ???.
template<class R, class A> R narrow_cast(const A& a)
{
R r = R(a);
if (A(r) != a) error(string("info loss"));
return r;
}
// random number generators. See 24.7.
inline default_random_engine& get_rand()
{
static default_random_engine ran; // note: not thread_local
return ran;
};
inline void seed_randint(int s) { get_rand().seed(s); }
inline int randint(int min, int max) { return uniform_int_distribution<>{min, max}(get_rand()); }
inline int randint(int max) { return randint(0, max); }
//inline double sqrt(int x) { return sqrt(double(x)); } // to match C++0x
// container algorithms. See 21.9. // C++ has better versions of this:
template<typename C>
using Value_type = typename C::value_type;
template<typename C>
using Iterator = typename C::iterator;
template<typename C>
// requires Container<C>()
void sort(C& c)
{
std::sort(c.begin(), c.end());
}
template<typename C, typename Pred>
// requires Container<C>() && Binary_Predicate<Value_type<C>>()
void sort(C& c, Pred p)
{
std::sort(c.begin(), c.end(), p);
}
template<typename C, typename Val>
// requires Container<C>() && Equality_comparable<C,Val>()
Iterator<C> find(C& c, Val v)
{
return std::find(c.begin(), c.end(), v);
}
template<typename C, typename Pred>
// requires Container<C>() && Predicate<Pred,Value_type<C>>()
Iterator<C> find_if(C& c, Pred p)
{
return std::find_if(c.begin(), c.end(), p);
}
#endif //H112
So to start with this problem I added the constant character from and constant string from_key just under all of the other constants in the calculator code.
const char from = 'f'; // file input read token
const string from_key = "from"; // file input read keyword
Then I added a new case for from token in the statement()'s function definiton
double statement()
{
Token t = ts.get();
switch (t.kind)
{
/.../
case from:
return input();
/.../
}
}
Ignore the function input() being returned from this case. That's kind of my main problem with this question. I will come back to it after the next part.
I followed it by adding a Token return for from's case in Token Token_stream::get() function's definition
Token Token_stream::get()
{
if (full)
{
/.../
}
char ch;
cin >> ch; //note that >> skips whitespace(space, newline, tab, etc)
switch (ch)
{
/.../
default:
if (isalpha(ch))
{
string s;
s += ch;
while (cin.get(ch) && (isalpha(ch) || isdigit(ch) || ch == '_')) s += ch;
cin.putback(ch);
if (s == declkey) return Token(let); //declaration keyword
else if (s == constdeclkey) return Token(constant);
else if (s == from_key) return Token(from);
return Token{ name, s };
}
error("Bad Token");
return 1;
}
}
After that I started writing the input() function which I mentioned seconds ago. It looks like this for now:
double input()
{
Token t = ts.get();
if (t.kind != name) error("read-file name expected in declaration");
string read_file = t.name;
ifstream ifs{ read_file + ".txt" };
if (!ifs) error("cannot open file " + read_file + ".txt");
while (ifs)
{
try
{
//idk what to do here
}
catch (exception& e)
{
cerr << e.what() << '\n';
clean_up_mess();
}
return 0;
}
}
So what I want to do is pretty simple.
I just want Token Token_stream::get() function to read input from ifs rather than cin, kind of like redirect the istream to ifs while its reading data from the file then switch it back to cin when its done. I'm thinking about calling the statement() function back here to print the evaluation on screen for now and then I might redirect it again to write the output to a file y.txt as it's mentioned in the question.
My issue is that I really don't know how to do this. I tried doing an if-else statement to switch istream from cin to ifs but getting ifs out from input()'s scope to Token Token_stream::get()'s scope is a big hurdle for me.
I need to check if number of letters "a" is equal to number of letters "b" using stack.
So i understand logic of this task, but my code doesn't work.
Logic:
If current letter == to letter in stack (s.pop()) or stack is empty then push into stack
else pop from stack
after end of cycle check size of stack. If it is empty so number of letters is equl, else not
I already have class stack
#include <string>
#include <iostream>
#include <cstdlib> // для system
using namespace std;
class stack {
public:
stack() {
ptr = 0;
}
~stack() {}
bool push(int val) {
if (ptr >= MAXSIZE) return false;
body[ptr++] = val; return true;
}
bool pop(int *val) {
if (ptr == 0) return false;
*val = body[--ptr]; return true;
}
bool empty() {
return ptr == 0;
}
private:
enum { MAXSIZE = 100 };
int body[MAXSIZE];
int ptr; // указатель на последний элемент
};
int main()
{
stack s;
std::string str;
std::cout << "Enter your ab string ";
getline(std::cin, str);
for (int c : str) {
if (c == s.pop(&c) || s.empty()) {
s.push(c);
}
else {
s.pop(&c);
}
}
if (s.empty()) {
cout << "YES\n";
system("pause");
return 0;
}
else {
cout << "NO\n";
system("pause");
}
}
result for abab, aabb, ab 'YES'
for aaabb, aba 'NO'
You need a method to look at current value on top of stack without popping it:
class stack {
...
int top() { // never use on an empty stack
return body[ptr-1];
}
...
};
That way you can write:
for (int c : str) {
// short circuit evaluation ensures that top is never called on an empty stack
if (s.empty() || (c == s.top()) {
s.push(c);
}
else {
s.pop(&c);
}
If you cannot, you must push back the popped value if it should not have been popped:
for (int c : str) {
int d;
if (! s.pop(&d)) { // s was empty
s.push(c);
}
else if (c == d) {
s.push(d); // should not have been popped
s.push(c);
}
}
You can push everytime you see a.
for (int c = 0; c < str.size() ; ++c) {
if (str[c] == 'a') s.push('a');
}
if ((s.size() * 2) == str.size()) cout << "YES\n"; else cout << "NO\n";
stack::size can be implemented this way:
int stack::size() {
return ptr;
}
My assignment is to make a binary expression tree to convert postfix expressions to infix expressions in C++. I originally coded all my work in my Xcode IDE and would periodically ssh to linprog4 in terminal to make sure it works there because it has to before I turn it in. I don't understand the errors that are popping up when I compile it using g++ -o proj4.x -std=c++11 proj4_driver.cpp BET.cpp
This assignment was due 2 weeks ago and unfortunately when I was turning in the tar file with all my files, I forgot to include the .tar extension. I don't think that would affect my files but now they aren't compiling and I don't understand the errors I am getting. Could someone skim through my code and see if I am missing anything? I've looked over my code and it doesn't look like I accidentally typed something randomly somewhere.
Here is a screenshot of the errors I am getting
BET.h
#ifndef BET_H
#define BET_H
using namespace std;
class BET {
private:
struct BinaryNode {
string data;
BinaryNode * parent;
BinaryNode * childLeft;
BinaryNode * childRight;
bool visited; // to tell if node has been visited to or not
// Construct a blank copy version BinaryNode when an
// object of BET is created
BinaryNode( const char & d = char{}, BinaryNode * p = NULL,
BinaryNode * l = NULL,
BinaryNode * r = NULL, bool v = false )
: data { d },
parent { p },
childLeft { l },
childRight { r },
visited { v } {}
// Construct a blank move version of BinaryNode when an
// an object of BET is created
BinaryNode( char && d, BinaryNode * p = NULL, BinaryNode * l = NULL,
BinaryNode * r = NULL, bool v = false )
: data { std::move(d) },
parent { p },
childLeft { l },
childRight { r },
visited { v } {}
}; // end of BinaryNode struct
public:
// constructors and destructor
BET();
BET( const string postfix );
BET( const BET & rhs );
~BET();
// help copy constructor
bool buildFromPostfix( const string postfix );
// copy assignment operator
const BET & operator=( const BET & rhs );
void printInfixExpression();
void printPostfixExpression();
size_t size();
size_t leaf_nodes();
bool empty();
bool isOperand(BinaryNode * n);
private:
BinaryNode *root;
size_t leaves, nodes;
bool useP;
void printInfixExpression( BinaryNode * n );
void makeEmpty( BinaryNode* & t );
BinaryNode * clone( BinaryNode * t ) const;
void printPostfixExpression( BinaryNode * n );
size_t size( BinaryNode * t );
size_t leaf_nodes( BinaryNode * t );
}; // end of BET class
#endif
BET.cpp
#include <iostream>
#include <stack>
#include <sstream>
#include <string>
#include "BET.h"
//using namespace std;
// default zero-param constructor
BET::BET() {
root = new BinaryNode;
leaves = 0;
nodes = 0;
}
// one-param constructor, where parameter "postfix" is a
// string containing a postfix expression. The tree should
// be built based on the postfix expression. Tokens in the
// postfix expression are separated by space
BET::BET(const string postfix) {
root = new BinaryNode;
buildFromPostfix(postfix);
}
// copy constructor
BET::BET(const BET & rhs) {
leaves = rhs.leaves;
nodes = rhs.nodes;
root = rhs.root;
}
// destructor
BET::~BET() {
makeEmpty(root);
leaves = nodes = 0;
}
bool BET::buildFromPostfix(const string postfix) {
// Create stack to hold variables
stack<BinaryNode *> s;
stack<BinaryNode> bet;
char token;
string temp;
int index = 1;
bool doubleDigit = false;
int opCount = 0, digitCount = 0;
//stringstream hexToInt;
// iterator through postfix
for (int i = 0; i < postfix.size(); ++i) {
// grab token at iterations index
token = postfix[i];
if ( (token > '0' && token < '9') || (token > 62 && token < 80)) {
// check to see if token is an operand
// create a dynamic object of BinaryNode
BinaryNode *operand = new BinaryNode;
// check to see if next index of postfix is digit
// if its not, then we know its a double digit
// this while loop should only continue as long as the
// next index is between 0 and 9
temp = postfix[i];
while (postfix[i + index] >= '0' && postfix[i + index] <= '9') {
temp += postfix[i + index];
index++;
doubleDigit = true;
}
if (doubleDigit == true) {
i += index;
doubleDigit = false;
index = 1;
operand->data = temp;
} else {
operand->data = postfix[i];
}
s.push(operand);
digitCount++;
} else if (token == '+' || token == '-' || token == '*' || token == '/'){
// check to see if token is operator
BinaryNode *operand = new BinaryNode;
operand->data = postfix[i];
operand->childLeft = s.top();
s.top()->parent = operand;
s.pop();
operand->childRight = s.top();
s.top()->parent = operand;
s.pop();
s.push(operand);
opCount++;
} else {
// if neither, must be space or other character
if (token == ' ') {
} else
return false;
}
}
if (digitCount <= opCount) {
return false;
}
root = s.top();
nodes = size();
//leaves = leaf_nodes();
// THINGS TO DO:
// Make error cases with if statements to return false at some point
return true;
}
// assignment operator
const BET & BET::operator=(const BET & rhs) {
root = clone(rhs.root);
return *this;
}
// public version of printInfixExpression()
// calls the private version of the printInfixExpression fuction
// to print out the infix expression
void BET::printInfixExpression() {
printInfixExpression(root);
}
// public version of printPostfixExpression()
// calls the private version of the printPostfixExpression function
// to print out the postfix expression
void BET::printPostfixExpression() {
printPostfixExpression(root);
}
// public version of size()
// calls the private version of the size function to return
// the number of nodes in the tree
size_t BET::size() {
return size(root);
}
// public version of leaf_nodes()
// calls the private version of leaf_nodes function to return
// the number of leaf nodes in the tree
size_t BET::leaf_nodes() {
return leaf_nodes(root);
}
// public version of empty()
// return true if the tree is empty. return false otherwise
bool BET::empty() {
if (nodes == 0) {
return true;
} else
return false;
}
// checks whether node is operand or not
bool BET::isOperand(BinaryNode * n) {
if (n->data != "+" && n->data != "-" && n->data != "*" && n->data != "/") {
return true;
} else
return false;
}
// private version of printInfixExpression
// print to the standard output the corresponding infix expression
void BET::printInfixExpression(BinaryNode * n) {
//BinaryNode * temp = NULL;
if (n != NULL ) {
printInfixExpression(n->childRight);
cout << n->data << " ";
printInfixExpression(n->childLeft);
}
/*
if (n != NULL && useP == true) {
printInfixExpression(n->childRight);
if (isOperand(n->parent) && n->parent != NULL && !n->childLeft) {
cout << "(";
}
cout << n->data << " ";
if (isOperand(n->parent) && n->parent != NULL && !n->childRight) {
cout << ")";
}
printInfixExpression(n->childLeft);
}
*/
}
// private method makeEmpty()
// delete all nodes in the subtree pointed to by n.
// Called by functions such as the destructor
void BET::makeEmpty(BinaryNode * & n) {
if (n != NULL) {
makeEmpty(n->childLeft);
makeEmpty(n->childRight);
delete n;
}
}
// private method clone()
// clone all nodes in the subtree pointed by n. Called by
// functions such as the assignment operator=
BET::BinaryNode * BET::clone(BinaryNode * n) const {
if (n != NULL) {
root->childRight = clone(n->childRight);
root->childLeft = clone(n->childLeft);
root->data = n->data;
}
return root;
}
// private method printPostfixExpression()
// print to the standard output the corresponding postfix expression
void BET::printPostfixExpression(BinaryNode * n) {
if (n != NULL) {
printPostfixExpression(n->childRight);
printPostfixExpression(n->childLeft);
cout << n->data << " ";
}
}
// private version of size()
// return the number of nodes in the subtree pointed by n
size_t BET::size(BinaryNode * n) {
if (n != NULL) {
size(n->childLeft);
size(n->childRight);
nodes++;
}
return nodes;
}
// return the number of leaf nodes in the subtree pointed by n
size_t BET::leaf_nodes(BinaryNode * n) {
if (n != NULL) {
leaf_nodes(n->childLeft);
leaf_nodes(n->childRight);
if (n->childLeft == NULL && n->childRight == NULL) {
leaves += 1;
}
}
return leaves;
}
Driver.cpp
#include "BET.cpp"
//using namespace std;
int main() {
string postfix;
// get a postfix expression
cout << "Enter the first postfix expression: ";
getline(cin, postfix);
// create a binary expression tree
BET bet1(postfix);
if (!bet1.empty()) {
cout << "Infix expression: ";
bet1.printInfixExpression();
cout << "\n";
cout << "Postfix expression: ";
bet1.printPostfixExpression();
cout << "\nNumber of nodes: ";
cout << bet1.size() << endl;
cout << "Number of leaf nodes: ";
cout << bet1.leaf_nodes() << endl;
// test copy constructor
BET bet2(bet1);
cout << "Testing copy constructor: ";
//bet2.printInfixExpression();
// test assignment operator
BET bet3;
bet3 = bet1;
cout << "Testing assignment operator: ";
//bet3.printInfixExpression();
}
cout << "Enter a postfix expression (or \"quit\" to quit): ";
while (getline(cin, postfix)) {
if (postfix == "quit") {
break;
}
if (bet1.buildFromPostfix(postfix)) {
cout << "Infix expression: ";
bet1.printInfixExpression();
cout << "Postfix expression: ";
bet1.printPostfixExpression();
cout << "Number of nodes: ";
cout << bet1.size() << endl;
cout << "Number of leaf nodes: ";
cout << bet1.leaf_nodes() << endl;
}
cout << "Enter a postfix expression (or \"quit\" to quit): ";
}
return 0;
}
Driver.cpp #include "BET.cpp" should be #include "BET.h"
Or (and this is just for completeness, not recommended), leave the include of the .cpp, but then only try to compile the one .cpp (as in g++ Driver.cpp) - since driver will include BET and so all your code is there and will build.
I'm writing a program that uses stacks to evaluate infix expressions read in from a file. Here is the code:
ptStack.h
#ifndef STACK
#define STACK
#include <cstdlib>
#include <iostream>
using namespace std;
template <class Item>
class Stack
{
public:
// CONSTRUCTOR
Stack( ) {top = NULL; count = 0;} // Inline
// MODIFIER MEMBER FUNCTIONS
void push( const Item& entry);
Item pop( );
// CONSTANT MEMBER FUNCTIONS
int size( ) {return count;} // Inline
bool is_empty( ) {return count == 0;} // Inline
private:
// DATA MEMBERS
struct Node
{
Item element;
Node *next;
};
Node *top;
int count;
};
#endif
ptStack.cpp
#include <cassert>
#include "ptStack.h"
using namespace std;
// MODIFIER MEMBER FUNCTIONS
template <class Item>
void Stack<Item>::push(const Item& entry)
{
Node *temp;
temp = new Node;
temp->element = entry;
temp->next = top->next;
top->next = temp;
count++;
}
template <class Item>
Item Stack<Item>::pop( )
{
Item value;
Node *temp;
value = top->next->element;
temp = top->next;
top->next = top->next->next;
delete temp;
count--;
return value;
}
infix.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "ptStack.h"
using namespace std;
// PRECONDITION: op must be an operator
// POSTCONDITION: returns precedence of operator
int pr(char op)
{
int precedence = 0;
switch (op)
{
case '+':
case '-': precedence = 1;
case '*':
case '/': precedence = 2;
default : precedence = 0;
}
return precedence;
}
// PRECONDITIONS: optr is one of the following: + - * /
// opnd1 and opnd2 are numbers from 1-9
// POSTCONDITIONS: returns the result of the chosen mathematical operation
int apply(char optr, int opnd1, int opnd2)
{
int result;
switch (optr)
{
case '+': result = opnd2+opnd1;
case '-': result = opnd2-opnd1;
case '*': result = opnd2*opnd1;
default : result = opnd2/opnd1;
}
return result;
}
int main()
{
Stack<int> numbers;
Stack<char> operators;
char ch, optr;
int num, opnd1, opnd2, prec = 0, newprec;
ifstream in_file; // input file
char in_file_name[20]; // name of input file (20 letter max)
cout << "Enter input file name: ";
cin >> in_file_name;
in_file.open(in_file_name); // opens file to read equations
while (!in_file.eof())
{
cout << "Expression: ";
while(in_file >> ch)
{
if (ch == ' ')
{}
else
{
num = ch - '0';
if((num < 10) && (num > 0))
{
cout << num << " ";
numbers.push(num);
}
else if((ch == '+') || (ch == '-') || (ch == '*') || (ch == '/'))
{
cout << ch << " ";
newprec = pr(ch);
if(newprec >= prec)
{
prec = newprec;
operators.push(ch);
}
else if(newprec < prec)
{
optr = operators.pop( );
opnd1 = numbers.pop( );
opnd2 = numbers.pop( );
num = apply(optr, opnd1, opnd2);
numbers.push(num);
operators.push(ch);
}
}
}
if(in_file.peek() == '\n')
break;
}
num = operators.size();
while(num != 0)
{
optr = operators.pop( );
opnd1 = numbers.pop( );
opnd2 = numbers.pop( );
num = apply(optr, opnd1, opnd2);
numbers.push(num);
num = operators.size( );
}
num = numbers.pop( );
cout << endl << "Value = " << num << endl << endl;
}
return 0;
}
It looks like everything should work but when I compile it, I get this error message.
> g++ -c ptStack.cpp
> g++ infix.cpp ptStack.o
Undefined first referenced
symbol in file
_ZN5StackIcE4pushERKc /var/tmp//ccwhfRAZ.o
_ZN5StackIiE4pushERKi /var/tmp//ccwhfRAZ.o
_ZN5StackIcE3popEv /var/tmp//ccwhfRAZ.o
_ZN5StackIiE3popEv /var/tmp//ccwhfRAZ.o
ld: fatal: symbol referencing errors. No output written to a.out
I've been able to pinpoint the errors to the callings of the push and pop member functions in the main of the infix file. I tried defining them inline in the header file like the size function and it compiles just fine using g++ infix.cpp ptStack.h, but then I get a segmentation fault when I run it.
Does anyone know how to fix either of these errors? Thanks in advance.
Just compile all the .cpp files with g++
g++ ptStack.cpp infix.cpp
I am using a modified version of Jesse Brown's shunting yard algorithm implementation. I am trying to modify the variable system to basically perform symbolic math instead of assigning double values to the variables. For example, instead of simply stating pi = 3.14, I would like it to just include pi in the solution. So 1+2+pi would result in 3+pi.
The code is as follows. I have just started to mess with it and haven't done a lot. Does anyone have any ideas?
// Source: http://www.daniweb.com/software-development/cpp/code/427500/calculator-using-shunting-yard-algorithm#
// Author: Jesse Brown
// Modifications: Brandon Amos
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include "shunting_yard.h"
using namespace std;
#define isvariablechar(c) (isalpha(c) || c == '_')
TokenQueue_t calculator::toRPN(const char* expr,
map<string, string>* vars,
map<string, int> opPrecedence) {
TokenQueue_t rpnQueue; stack<string> operatorStack;
bool lastTokenWasOp = true;
// In one pass, ignore whitespace and parse the expression into RPN
// using Dijkstra's Shunting-yard algorithm.
while (*expr && isspace(*expr)) ++expr;
while (*expr) {
if (isdigit(*expr)) {
// If the token is a number, add it to the output queue.
char* nextChar = 0;
double digit = strtod(expr, &nextChar);
# ifdef DEBUG
cout << digit << endl;
# endif
rpnQueue.push(new Token<double>(digit));
expr = nextChar;
lastTokenWasOp = false;
}
else if (isvariablechar(*expr)) {
// If the function is a variable, resolve it and
// add the parsed number to the output queue.
if (!vars) {
//throw domain_error(
//"Detected variable, but the variable map is null.");
}
stringstream ss;
ss << *expr;
++expr;
while (isvariablechar(*expr)) {
ss << *expr;
++expr;
}
string key = ss.str();
map<string, string>::iterator it = vars->find(key);
if (it == vars->end()) {
//throw domain_error(
//"Unable to find the variable '" + key + "'.");
}
string val = vars->find(key)->second;
# ifdef DEBUG
cout << val << endl;
# endif
rpnQueue.push(new Token<string>(val));;
lastTokenWasOp = false;
}
else {
// Otherwise, the variable is an operator or paranthesis.
switch (*expr) {
case '(':
operatorStack.push("(");
++expr;
break;
case ')':
while (operatorStack.top().compare("(")) {
rpnQueue.push(new Token<string>(operatorStack.top()));
operatorStack.pop();
}
operatorStack.pop();
++expr;
break;
default:
{
// The token is an operator.
//
// Let p(o) denote the precedence of an operator o.
//
// If the token is an operator, o1, then
// While there is an operator token, o2, at the top
// and p(o1) <= p(o2), then
// pop o2 off the stack onto the output queue.
// Push o1 on the stack.
stringstream ss;
ss << *expr;
++expr;
while (*expr && !isspace(*expr) && !isdigit(*expr)
&& !isvariablechar(*expr) && *expr != '(' && *expr != ')') {
ss << *expr;
++expr;
}
ss.clear();
string str;
ss >> str;
# ifdef DEBUG
cout << str << endl;
# endif
if (lastTokenWasOp) {
// Convert unary operators to binary in the RPN.
if (!str.compare("-") || !str.compare("+")) {
rpnQueue.push(new Token<double>(0));
}
else {
//throw domain_error(
//"Unrecognized unary operator: '" + str + "'.");
}
}
while (!operatorStack.empty() &&
opPrecedence[str] <= opPrecedence[operatorStack.top()]) {
rpnQueue.push(new Token<string>(operatorStack.top()));
operatorStack.pop();
}
operatorStack.push(str);
lastTokenWasOp = true;
}
}
}
while (*expr && isspace(*expr)) ++expr;
}
while (!operatorStack.empty()) {
rpnQueue.push(new Token<string>(operatorStack.top()));
operatorStack.pop();
}
return rpnQueue;
}
double calculator::calculate(const char* expr,
map<string, string>* vars) {
// 1. Create the operator precedence map.
map<string, int> opPrecedence;
opPrecedence["("] = -1;
opPrecedence["<<"] = 1; opPrecedence[">>"] = 1;
opPrecedence["+"] = 2; opPrecedence["-"] = 2;
opPrecedence["*"] = 3; opPrecedence["/"] = 3;
// 2. Convert to RPN with Dijkstra's Shunting-yard algorithm.
TokenQueue_t rpn = toRPN(expr, vars, opPrecedence);
// 3. Evaluate the expression in RPN form.
stack<double> evaluation;
while (!rpn.empty()) {
TokenBase* base = rpn.front();
rpn.pop();
Token<string>* strTok = dynamic_cast<Token<string>*>(base);
Token<double>* doubleTok = dynamic_cast<Token<double>*>(base);
if (strTok) {
string str = strTok->val;
/*if (evaluation.size() < 2) {
throw domain_error("Invalid equation.");
}*/
if (str.compare("pi")){
cout << "its pi!" << endl;
}
double right = evaluation.top(); evaluation.pop();
double left = evaluation.top(); evaluation.pop();
if (!str.compare("+")) {
evaluation.push(left + right);
}
else if (!str.compare("*")) {
evaluation.push(left * right);
}
else if (!str.compare("-")) {
evaluation.push(left - right);
}
else if (!str.compare("/")) {
evaluation.push(left / right);
}
else if (!str.compare("<<")) {
evaluation.push((int)left << (int)right);
}
else if (!str.compare(">>")) {
evaluation.push((int)left >> (int)right);
}
else {
cout << "Unknown Operator" << endl;
//throw domain_error("Unknown operator: '" + str + "'.");
}
}
else if (doubleTok) {
evaluation.push(doubleTok->val);
}
else {
//throw domain_error("Invalid token.");
}
delete base;
}
return evaluation.top();
}