Question

In: Computer Science

Part 1: Stack Create a New Project and give your project a name, say Lab6a. Download...

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;
  
}

Please answer in c++

Solutions

Expert Solution

The code provided below, follows the exact algorithm given in the problem description, no extra thing have been added. Please note that the algorithm in the last gives "The code is correct" even when the number of opening symbol is equal to number of closing symbol, no matter what the order is. Also there was a confusion in the algorithm that after showing the errors, we had to end the program or had to go on till the end of file. The code just follows the algorithm and read the file till the last character, and if there is mismatch shows error and continue reading the next character. And in last prints the output. If the both testfiles will be generated according to the algorithm it will give the correct output.

for ex:

input file : " { ] "

the code will give a error of not equal but prints the code is correct (as for the algorithm says as the closing symbol comes, first pop the stack ( " { " ) and then match if it is corresponding to the closing symbol just read. so it will give the "not equal error", but as the stack is now empty after the stack, so the algorithm says the code is correct.

If you need the code which gives the code incorrect for this input file, the algorithm will be different, you can ask for that in comment section.

CODE(StackMain.cpp reamaining two files(StackArr.cpp & StackArr.h ) will be same):

// StackMain.cpp

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

using namespace std;

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;

}

void solve(string str){
    int n = str.length();       // CALCULATE THE LENGTH OF STRING IN THE FILE
    StackArr mystack(n);        // MADE THE EMPTY STACK OF SIZE == LENGTH OF STRING
    for(int i=0;i<n;i++){
        if (str[i]=='(' || str[i]=='{' || str[i]=='[')  // IF INPUT SYMBOL ENCOUNTERED JUST PUSH IT
            mystack.push(str[i]);
        else if(str[i]==')' || str[i]=='}'|| str[i]==']'){ // IF CLOSING SYMBOL
            if (mystack.isEmpty())                         // CHECK IF STACK IS EMPTY THEN SHOW ERROR
                cout<<"Error: Empty stack"<<endl;
            else{ 
                char ch = mystack.pop();                   // ELSE POP THE STACK
                if ((ch=='(' && str[i]==')') || (ch=='{' && str[i]=='}') || (ch=='[' && str[i]==']'))  // CHECK IF THE POPPED SYMBOL CORRESPONDS TO THE CLOSED SYMBOL READ IF IT IS CONTINUE
                    continue;
                else                                       // ELSE SHOW THE ERROR NOT EQUAL
                    cout<<"Error: Not equal"<<endl;

            }
        }

    }
    if (mystack.isEmpty())                             // AFTER READING ALL THE CHARACTERS, CHECK IF THE STACK IS EMPTY IF IT IS PRINT THE CODE IS CORRECT
        cout<<"The code is correct"<<endl;
    else
        cout<<"The code is incorrect"<<endl;           // ELSE PIRNT CODE IS INCORRECT


}

int main(){

    string str = readFile();
    cout<<"input file content: "<<str<<endl;
    solve(str);

    return 0;
}


OUTPUT(SAMPLE):

NOTE: In case of any query or doubt, or you want any modification in the code, you can mention that in comment section. HAPPY LEARNING!!


Related Solutions

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 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...
Part 1: Create a character array and save your first and last name in it
PROGRAMMING IN C:Part 1:Create a character array and save your first and last name in itNote: You can assign the name directly or you can use the scanf function.Display your name on the screen.Display the address (memory location) in hexadecimal notation of the array. (hint: use %p)Use a for loop to display each letter of your name on a separate line.Part 2:Create a one dimensional array and initialize it with 10 integers of your choice.Create a function and pass the...
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...
Lab 7   - Rectangle class-   (Lec. 7) 1.) Create a new project and name it:    Rectangle...
Lab 7   - Rectangle class-   (Lec. 7) 1.) Create a new project and name it:    Rectangle /* OUTPUT: Enter the width of the court: 60 Enter the length of the court: 120 The width of the court is 60 feet. The length of the court is 120 feet. The area of the court is 7200 square feet. Press any key to continue . . . */ 2.) Create the following 3 files: Rectangle.h Rectangle.cpp Source.cpp 3.) Write a program that...
1. Start a new Visual Studio project and name it GradeAppa. Make sure your project...
1. Start a new Visual Studio project and name it GradeAppa. Make sure your project is a web projectb. Make sure it is using C#2. Add a new folder and name it Grades_Logic3. Inside this new folder create a new web form called “Grades”4. Add a label to hold text “Enter Grade”5. Add a text field in front of the label to receive the grade6. Add another label in a new line to display the text “Participation”7. Place a drop-down...
Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack...
Exercise 3: Stack Write a program in Java to manipulate a Stack List: 1. Create Stack List 2. Display the list 3. Create the function isEmply 4. Count the number of nodes 5. Insert a new node in the Stack List. 6. Delete the node in the Stack List. 7. Call all methods above in main method with the following data: Test Data : Input the number of nodes : 4 Input data for node 1 : 5 Input data...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT