Question

In: Computer Science

Stack Create a New Project and give your project a name, say. Download the given source...

Stack

  1. Create a New Project and give your project a name, say.
  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".

Code below:

//////////////////////////////////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
#pragma once

//////////////////////////////////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

Hi there,

I have completed the code as per your requirements. I have made some changes to your above starter files as they were writing unwanted output to the terminal.

The code:

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

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()) {
return -1;
}
else
return values[stackTop--];
}

char StackArr::top() const {
if (isEmpty()) {
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;
  
}
//Code starts
int main()
{
   ifstream infile;
   string file;
   cout<<"Please enter the file name : ";
   cin>>file;
   //opening the file
    infile.open(file);
    //check if file exists or not
    if (!infile.is_open())
    {
        cout<<"\nFile did not open!! please try again...\n";
        exit(0);
    }
    char ch;
    //create the stack
    StackArr st = StackArr(100);
    //bool to track if the code is correct or not
    bool correct=true;
    //read the file character by character
    while(infile.get(ch))
    {
        //if it is a opening bracket
        if(ch=='(' || ch=='{' || ch=='[')
            st.push(ch);
        //if it is a closing bracket     
        if(ch==')' || ch=='}' || ch==']')
        {
            //if the closing bracket matches the opening bracket
            if(!st.isEmpty() && (ch==')' && st.top() == '(') || (ch=='}' && st.top() == '{') || (ch==']' && st.top() == '['))
              st.pop();
          else
          {
              correct = false;
              break;
          }
      }
   }
   if(!correct)
   {
      cout<<"\nError: Not equal";
   }
   else if(!st.isEmpty())
      cout<<"\nThe code is incorrect";
   else
      cout<<"\nThe code is correct";
   cout<<"\n";
   //close the file
   infile.close();
   return 0;
}                         

The Code(screenshot) :   

The test file(Screenshot) :   

The Output(Screenshot) :

Hope you liked my answer. If you have any doubts, please feel free to ask in the comment section.

Happy Coding :)


Related Solutions

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....
Create a project for this assignment. You can name it assignment02 if you wish. Download the...
Create a project for this assignment. You can name it assignment02 if you wish. Download the database file pizza-190807A.sqlite into the top level of the project. Create the pizza_services.py module first and put in the code given in the assignment. Using this code ensures that you can use the services in a similar way to the example. The assignment suggests adding a method customer to the class. This will return a list of rows from the customer table in the...
Download the data type class named as MathOperation:(given below) Create the project of part 2 then...
Download the data type class named as MathOperation:(given below) Create the project of part 2 then add class as a data type class and class MathCalculator_yourLastName as a driver class with main() of part 2 a. Draw UML of class MathOperation (See the topic about UML at TIP FOR LAB on eCampus) b. Create the pseudo-code or draw flowchart of the main of a driver class based on the requirement listed below (see the topic about pseudo-code or flowchart at...
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...
Create a new file name condition_quiz.py. Add a comment with your name and the date. Prompt...
Create a new file name condition_quiz.py. Add a comment with your name and the date. Prompt the user to enter the cost. Convert the input to a float. Prompt the user for a status. Convert the status to an integer Compute the special_fee based on the status. If the status is 0, the special_fee will be 0.03 of the cost. Else if the status is 1, the special_fee will be 0.04 of the cost. Else if the status is 2,...
python Create a new file name condition_quiz.py. Add a comment with your name and the date....
python Create a new file name condition_quiz.py. Add a comment with your name and the date. Prompt the user to enter the cost. Convert the input to a float. Prompt the user for a status. Convert the status to an integer Compute the special_fee based on the status. If the status is 0, the special_fee will be 0.03 of the cost. Else if the status is 1, the special_fee will be 0.04 of the cost. Else if the status is...
Using the Stack ADT: Create a program that uses a stack. Your program should ask the...
Using the Stack ADT: Create a program that uses a stack. Your program should ask the user to input a few lines of text and then outputs strings in reverse order of entry. (Optional) Create a similar program that uses a stack. Your new program should ask the user to input a line of text and then it should print out the line of text in reverse. To do this your application should use a stack of Character. In Java...
HW_6a - Read a text file Create a new C++ project and name it as:   Numbers...
HW_6a - Read a text file Create a new C++ project and name it as:   Numbers Create a text file and     save it as:   data.txt Create and save the file      in a C++ project      in the Resource folder. Enter the following numbers:        3                                                              4                                                              5       Note:   After you enter the 5, don’t press the enter key. Save and close the file. Add another file and name it:   Source.cpp Write one statement that declares a file...
Once the form in this file is submitted, create a new paragraph that will stack on...
Once the form in this file is submitted, create a new paragraph that will stack on top of the existing paragraphs and will contain the data entered into the textarea. Each new paragraph should have the class 'tweet' applied to it. *Hint: Remember to use return false; to stop the form submission from reloading the page. <!DOCTYPE html> <html> <head>    <title>Simple Twitter</title>    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">    <style>    .tweet{border-top:1px solid #dedede; padding:20px;}    </style>    <script...
Once the form in this file is submitted, create a new paragraph that will stack on...
Once the form in this file is submitted, create a new paragraph that will stack on top of the existing paragraphs and will contain the data entered into the textarea. Each new paragraph should have the class 'tweet' applied to it. *Hint: Remember to use return false; to stop the form submission from reloading the page. <!DOCTYPE html> <html> <head> <title>Simple Twitter</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <style> .tweet{border-top:1px solid #dedede; padding:20px;} </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body class="container" style="width:50%"> <h1>Twitter</h1>...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT