Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

This assignment tests the concepts of: Stacks Templates Objective You will write a program that acts as a simple calculator, reading a file (filename provided

This assignment tests the concepts of:

Stacks

Templates

Objective

You will write a program that acts as a simple calculator, reading a file (filename provided as argument) that contains an arithmetic expression on each line. The program evaluates these expressions and prints the values to cout. The expressions are postfix expressions (as described on page 331 of the text).

All your work should be concentrated on the process_line function, no other parts of labcalc.cpp should have to be modified. In fact, only a small section of this function needs to be written.

However, the calculator depends on the Stack class, which is expected to be templated

A non-Templated stack class shell is provided, finish implementing it and modify it so that it works for any type.

In order for you to be able to do this, you will also need to template Node.

You should not need to add any new functions

Submission

Submit only the following to Blackboard: Node.h, Stack.h, and labstackt.cpp

Submitted assignments without the above file named correctly will render your assignment as uncompilable and will be detrimental to your assignment grade.

Additional Criteria

Memory leaks will lead to grade leaks on this assignment. No heap memory should be in use when the main function reaches the return 0.

Absolutely no #includes should be added

No recursion!

Example Output

12 34 nan 12 done

---------------------------------------------------------------------------

#ifndef NODE_H_ #define NODE_H_ namespace DSLab { class Node { public: typedef int value_type; Node(const value_type& d = value_type(), Node * n = nullptr) { data = d; next = n; } value_type data; Node * next; }; } /* namespace DSLab */ #endif /* NODE_H_ */

---------------------------------------------------------------

#ifndef STACKT_H_ #define STACKT_H_ #include  #include "Node.h" namespace DSLab { class Stack { public: Stack() { head = nullptr; nodeCount = 0; } ~Stack(); Node::value_type top() const; void push(const Node::value_type&); void pop(); void empty(); std::size_t size() const; private: Node * head; std::size_t nodeCount; }; } /* namespace DSLab */ #endif /* STACKT_H_ */

-------------------------------------------------------------------------

#include "Stack.h" namespace DSLab { Stack::~Stack() { while ( head != nullptr ) { Node * temp = head; head = head->next; delete temp; } } Node::value_type Stack::top() const { return head->data; } void Stack::push(const Node::value_type& data) { head = new Node(data,head); } void Stack::pop() { Node * temp = head; head = head->next; delete temp; } } /* namespace DSLab */

--------------------------------------------------------------------------------

 #include "Stack.h" namespace DSLab { Stack::~Stack() { while ( head != nullptr ) { Node * temp = head; head = head->next; delete temp; } } Node::value_type Stack::top() const { return head->data; } void Stack::push(const Node::value_type& data) { head = new Node(data,head); } void Stack::pop() { Node * temp = head; head = head->next; delete temp; } } /* namespace DSLab */

------------------------------------------------------------------------

This is the main file

#include

#include

#include

#include // Provides strchr

#include

#include

#include "StackT.h"

#include "Node.h"

using namespace DSLab;

/*

Preconditon: argc is the number of arguments provided. Right is the expected number of arguments, ignoring the first one (ie: name of exe)

that is ALWAYS present. Usage is the error message that is displayed if number of args does not match.

Postcondition: Outputs message and returns false when it fails to validate, true otherwise. */

bool validate_argc(int argc, int right, const char usage[] );

//A function that opens a file for input and checks that the opening process did not fail. The specification for this function is:

// Postcondition: The ifstream f has been opened for

// reading using the given filename. If any errors

// occurred then an error message has been printed

// and the program has been halted.

void open_for_read(std::ifstream& f, const char filename[ ]);

//A boolean function that determines whether a specified file still has valid input. The specification is:

// Postcondition: The return value is true if f still has

// more valid input to read; otherwise the return

// valid is false.

bool is_more(std::istream& f);

/*

Reads the next line of input (including the newline character at the end of the line). It treats this input line as an arithmetic expression.

If the expression has an error (such as division by zero), then the function sets okay to false and leaves answer unchanged.

Otherwise, the function sets okay to true and sets answer to the value of the expression.

Here are a few considerations:

The input expressions are postfix expressions.

Use the evaluation algorithm from Figure 7.10 in the textbook.

The possible errors that will cause okay to be set to false:

(a) division by zero,

(b) an operation symbol is read but the stack does not have at least two numbers,

(c) the entire expression has been read and evaluated but the numbers stack does not have exactly one number on it.

*/

double process_line(std::istream& f);

int main(int argc, char *argv[]) {

if ( validate_argc(argc,1, "Usage: calc input_file") ) {

std::ifstream input;

open_for_read(input, argv[1]);

//char c;

double answer;

while ( is_more(input) ) {

answer = process_line(input);

std::cout << answer << std::endl;

}

input.close();

std::cout << " done "; // prints !!!Hello World!!!

}

return 0;

}

bool validate_argc(int argc, int right, const char usage[] ) {

if ( (argc-1) == right )

return true;

std::cerr << usage << std::endl;

return false;

}

void open_for_read(std::ifstream& f, const char filename[ ]) {

f.open(filename);

if ( f.fail() ) {

std::cerr << "Could not open input file" << std::endl;

std::exit(1);

}

}

bool is_more(std::istream& f) {

return f && f.peek() != EOF;

}

double process_line(std::istream& f) {

double answer = std::nan("Invalid"); //Doubles can actually be set to nan, which stands for, "Not a Number"

const char DECIMAL = '.';

Stack numbers;

double number;

char operation;

//Ignore initial newlines

while ( f.peek( ) == ' ' )

f.ignore(1);

// Loop continues while istream is not bad (tested by ins) and next character is not newline.

while ( f && f.peek( ) != ' ' ) {

if (isdigit(f.peek( )) || (f.peek( ) == DECIMAL))

{

f >> number;

numbers.push(number);

}

else if (std::strchr("+-/*", f.peek( )) != NULL) {

double operand1, operand2;

f >> operation;

if ( numbers.size() >= 2 ) { //Stack must have at least two numbers to pop

//Postifix notation

//This is when you do the MATH option

//Pop the two numbers and do the operation

//STUDENT IMPLEMENTS

double operand2 = answer.top();

answer.pop();

double operand1 = result.top();

answer.pop();

if (input == "+")

{

answer.push(operand1 + operand2);

}

else if(input == "-")

{

answer.push(operand1 - operand2);

}

else if(input == "*")

{

answer.push(operand1 * operand2);

}

else

{

answer.push(operand1 / operand2);

}

else if (number == "p")

cout << numbers.top() << " ";

else if(number =="q")

return 0;

}

} else {

//Invalid, not enough numbers to do binary operation

//Ignore the rest of the LINE

f.ignore(std::numeric_limits::max(), ' ');

return answer;

}

} else {

//Ignore all other characters, such as spaces

f.ignore(1);

}

}

//Size must be 1, otherwise invalid

if ( numbers.size() == 1 )

{

answer = numbers.top();

numbers.pop();

}

return answer;

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions