Question

In: Computer Science

Please complete it in C++ Part 1: Stack Create a New Project and give your project...

Please complete it in C++

Part 1: Stack

  1. Create a New Project and give your project a name, say Lab6a.
  2. Download the given source files StackArr.h and StackArr.cpp from Moodle and save them to your Lab6a folder. Also import them to your project.
  3. Add a source file to your project, called StackMain.cpp and implement your program according to the following:
    1. Prompt the user to input a program filename.
    2. Open the file and check if every right brace (i.e. }), bracket (i.e. ]), and parenthesis (i.e. )) in the file correspond to its left counterpart or not.
    3. If the program file passed the checking, output "The code is correct". Otherwise, output "The code is incorrect".

The algorithm for checking is as follows:

  1. Make an empty stack
  2. Read characters until the end of program file
    1. if the character is an opening symbol, push it onto the stack;
    2. if it is a closing symbol and if the stack is empty, output "Error: Empty stack";
    3. otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, output "Error: Not equal".

At the end of the file, if the stack IS NOT EMPTY, output "The code is incorrect". Otherwise, output "The code is correct".

Use the provided files, testfile1.txt and testfile2.txt to test your program. The code file testfile1.txt is correct, while the code file testfile2.txt is incorrect.

Useful code:

#include <fstream>

string readFile() {

     string tempString = "";

     string filename;

    

     cout << "Input file name: ";

     cin >> filename;

     ifstream inputFile(filename);

    

     // Prompt user again if wrong filename received

     while (!inputFile.good()) {

          cout << "Wrong file name, input again please: ";

          cin >> filename;

          inputFile.open(filename);

     }

    

     // Append all lines from the file into a long string

     while ((!inputFile.eof())) {

          string str;

          getline(inputFile, str);

          tempString += str;

     }

    

     return tempString;

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include "StackArr.h"
#include <string>
#include <iostream>

using namespace std;

StackArr::StackArr(int size) {
   maxTop = size;
   values = new char[size];
   stackTop = -1;
}

StackArr::~StackArr() {
   delete[] values;
}

bool StackArr::isEmpty() const {
   return stackTop == -1;
}

bool StackArr::isFull() const {
   return stackTop == maxTop;
}

void StackArr::push(const char& x) {
   if (isFull())
       cout << "Error! The stack is full!" << endl;
   else
       values[++stackTop] = x;
}

char StackArr::pop() {
   if (isEmpty()) {
       cout << "Error! The stack is empty!" << endl;
       return -1;
   }
   else
       return values[stackTop--];
}

char StackArr::top() const {
   if (isEmpty()) {
       cout << "Error! The stack is empty!" << endl;
       return -1;
   }
   else
       return values[stackTop];
}

void StackArr::displayStack() const {
   cout << "Top -->";
   for (int i = stackTop; i >= 0; i--)
       cout << "\t|\t" << values[i] << "\t|" << endl;
   cout << "\t|---------------|" << endl;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include "StackArr.h"
#include <string>
#include <iostream>

using namespace std;

StackArr::StackArr(int size)
   maxTop = size;
   values = new char[size];
   stackTop = -1;
}

StackArr::~StackArr() {
   delete[] values;


bool StackArr::isEmpty() const {
   return stackTop == -1;
}

bool StackArr::isFull() const {
   return stackTop == maxTop;
}

void StackArr::push(const char& x) {
   if (isFull())
       cout << "Error! The stack is full!" << endl;
   else
       values[++stackTop] = x;
}

char StackArr::pop() {
   if (isEmpty()) {
       cout << "Error! The stack is empty!" << endl;
       return -1;
   }
   else
       return values[stackTop--];
}

char StackArr::top() const {
   if (isEmpty()) {
       cout << "Error! The stack is empty!" << endl;
       return -1;
   }
   else
       return values[stackTop];
}

void StackArr::displayStack() const {
   cout << "Top -->";
   for (int i = stackTop; i >= 0; i--)
       cout << "\t|\t" << values[i] << "\t|" << endl;
   cout << "\t|---------------|" << endl;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//StackArr.h

#ifndef STACKARR_H
#define STACKARR_H

class StackArr {
private:
   int maxTop;
   int stackTop;
   char *values;

public:
   StackArr(int);
   ~StackArr();
   bool isEmpty() const;
   bool isFull() const;
   char top() const;
   void push(const char& x);
   char pop();
   void displayStack() const;
};

#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////StackArr.cpp

#include "StackArr.h"
#include <string>
#include <iostream>

using namespace std;

StackArr::StackArr(int size) {
   maxTop = size;
   values = new char[size];
   stackTop = -1;
}

StackArr::~StackArr() {
   delete[] values;
}

bool StackArr::isEmpty() const {
   return stackTop == -1;
}

bool StackArr::isFull() const {
   return stackTop == maxTop;
}

void StackArr::push(const char& x) {
   if (isFull())
       cout << "Error! The stack is full!" << endl;
   else
       values[++stackTop] = x;
}

char StackArr::pop() {
   if (isEmpty()) {
       cout << "Error! The stack is empty!" << endl;
       return -1;
   }
   else
       return values[stackTop--];
}

char StackArr::top() const {
   if (isEmpty()) {
       cout << "Error! The stack is empty!" << endl;
       return -1;
   }
   else
       return values[stackTop];
}

void StackArr::displayStack() const {
   cout << "Top -->";
   for (int i = stackTop; i >= 0; i--)
       cout << "\t|\t" << values[i] << "\t|" << endl;
   cout << "\t|---------------|" << endl << endl;
  
}

Solutions

Expert Solution

Below is the code for StackMain.cpp

#include <fstream>
#include<string>
#include"StackArr.h"
#include<iostream>
using namespace std;

string readFile()
{
        string tempString = "";
        string filename;
        cout << "Input file name: ";
        cin >> filename;
        ifstream inputFile(filename);
        while (!inputFile.good())
        {
                cout << "Wrong file name, input again please: ";
                cin >> filename;
                inputFile.open(filename);
        }

        while ((!inputFile.eof()))
        {
                string str;
                getline(inputFile, str);
                tempString += str;
        }

        return tempString;
}


void areParanthesisBalanced(string dataFromFile)
{
        StackArr stack(dataFromFile.length() + 1);
        char x;

        // Traversing the dataFromFile 
        for (int i = 0; i < dataFromFile.length(); i++)
        {
                if (dataFromFile[i] == '(' || dataFromFile[i] == '[' || dataFromFile[i] == '{')   //if opening bracket then push in stack
                {
                        // Push the element in the stack 
                        stack.push(dataFromFile[i]);
                        continue;
                }

                // IF current current character is not opening 
                // bracket, then it must be closing. So stack 
                // cannot be empty at this point. 
                if (stack.isEmpty())
                {
                        cout << "Error: Empty stack";
                        return;
                }
                
                switch (dataFromFile[i]) {
                case ')':

                        // Store the top element in a 
                        x = stack.top();
                        stack.pop();
                        if (x == '{' || x == '[')
                        {
                                cout << "Error: Not equal";
                                return;
                        }
                        break;

                case '}':

                        // Store the top element in b 
                        x = stack.top();
                        stack.pop();
                        if (x == '(' || x == '[')
                        {
                                cout << "Error: Not equal";
                                return;
                        }
                        break;

                case ']':

                        // Store the top element in c 
                        x = stack.top();
                        stack.pop();
                        if (x == '(' || x == '{')
                        {
                                cout << "Error: Not equal";
                                return;
                        }
                        break;
                }
        }

        // Check Empty Stack 
        if (stack.isEmpty())
        {
                cout << "The code is correct.";
        }
        else
        {
                cout <<"The code is incorrect";
        }
}
int main()
{
        string dataFromFile = readFile();    /* read data from file */
        areParanthesisBalanced(dataFromFile);  /* call functio to check if parenthesis are valid or not */
        return 0;
}

output screenshot with validinput.txt

outputscreenshot with invalidinput.txt


Related Solutions

Please complete it in C++ Part 2: Queue Create a New Project and give your project...
Please complete it in C++ Part 2: Queue Create a New Project and give your project a name, say Lab6b. Download the given source files StackArr.h, StackArr.cpp, QueueArr.h and QueueArr.cpp from Canvas and save them to your Lab6b folder. Also import them to your project. Add a source file to your project, called QueueMain.cpp and implement your program according to the following: prompt the user to input a string; change each uppercase letter to lowercase; place each letter both in...
Part 1: Stack Create a New Project and give your project a name, say Lab6a. Download...
Part 1: Stack Create a New Project and give your project a name, say Lab6a. Download the given source files StackArr.h and StackArr.cpp from Moodle and save them to your Lab6a folder. Also import them to your project. Add a source file to your project, called StackMain.cpp and implement your program according to the following: Prompt the user to input a program filename. Open the file and check if every right brace (i.e. }), bracket (i.e. ]), and parenthesis (i.e....
Stack Create a New Project and give your project a name, say. Download the given source...
Stack Create a New Project and give your project a name, say. Download the given source files StackArr.h and StackArr.cpp from Moodle and save them to your Lab6a folder. Also import them to your project. Add a source file to your project, called StackMain.cpp and implement your program according to the following: Prompt the user to input a program filename. Open the file and check if every right brace (i.e. }), bracket (i.e. ]), and parenthesis (i.e. )) in the...
Create a C program that performs the following (please comment the codes): a) Create a Stack...
Create a C program that performs the following (please comment the codes): a) Create a Stack ADT. Stack should be implemented using the linked list. b) Enter 10 random integer numbers between 0 to 50 in the stack. c) After pushing each element, print the content of the top of the stack. c) Then pop out those 10 integer numbers and print those numbers. d) Finally destroy the Stack.
Please follow the instructions and solve it by c++ Close the project and create a new...
Please follow the instructions and solve it by c++ Close the project and create a new one called 'Lab0-Part3' with the same options as in the previous step. Write a C++ program that does the following: Creates a 100-element array, either statically or dynamically Fills the array with random integers between 1 and 100 inclusive Then, creates two more 100-element arrays, one holding odd values and the other holding even values. Prints both of the new arrays to the console.
C++ Please complete based on the code below. Declare another stack object to the code in...
C++ Please complete based on the code below. Declare another stack object to the code in main(). Add a stack operator called CopyStack to the Stack class which, when executed, copies the contents of the first stack into the second stack. Modify your menu so that this option is available. The menu should also allow the second stack to be printed, pushed, popped, and so forth, just like with the first stack. #include using namespace std; #define MAXSize 10 class...
********************C# C# C#******************** Part A: Create a project with a Program class and write the following...
********************C# C# C#******************** Part A: Create a project with a Program class and write the following two methods(headers provided) as described below: 1. A Method, public static int InputValue(int min, int max), to input an integer number that is between (inclusive) the range of a lower bound and an upper bound. The method should accept the lower bound and the upper bound as two parameters and allow users to re-enter the number if the number is not in the range...
In the Stack Module I gave you a project that shows how to create a Stack...
In the Stack Module I gave you a project that shows how to create a Stack using doubly linked nodes. StackWithDoublyLinkedNodes.zip It is a template class that needs the Node class. You must use this same Node class (no alterations) to create a Queue class . public class Queue <T>{ } Use the NetBeans project above as an example. I have put a driver program (q1.java) in the module. Also here:  q1.java This driver program should then run with your Queue...
In the Stack Module I gave you a project that shows how to create a Stack...
In the Stack Module I gave you a project that shows how to create a Stack using doubly linked nodes. StackWithDoublyLinkedNodes.zip It is a template class that needs the Node class. You must use this same Node class (no alterations) to create a Queue class . public class Queue <T>{ } Use the NetBeans project above as an example. I have put a driver program (q1.java) in the module. Also here:  q1.java This driver program should then run with your Queue...
Part 1 – Classes and objects Create a new Java project called usernamePart1 in NetBeans. In...
Part 1 – Classes and objects Create a new Java project called usernamePart1 in NetBeans. In my case the project would be called rghanbarPart1. Select the option to create a main method. Create a new class called Vehicle. In the Vehicle class write the code for: • Instance variables that store the vehicle’s make, model, colour, and fuel type • A default constructor, and a second constructor that initialises all the instance variables • Accessor (getters) and mutator (setters) methods...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT