Question

In: Computer Science

C++ Write a program that prompts for a file name and then reads the file to...

C++ Write a program that prompts for a file name and then reads the file to check for balanced curly braces, {; parentheses, (); and square brackets, []. Use a stack to store the most recent unmatched left symbol. The program should ignore any character that is not a parenthesis, curly brace, or square bracket. Note that proper nesting is required. For instance, [a(b]c) is invalid. Display the line number the error occurred on.

These are a few of the files that will be called, each named input1.cpp , input2.cpp and so on until input6.cpp -

input1.cpp

#include <iostream>

using namespace std;

void main (void)
{
   cout << "Hello World!" << endl;

}

input2.cpp

#include <iostream>

using namespace std;

void main (void)
   cout << "Hello World!" << endl;

}

Solutions

Expert Solution

----------------Stack.h-----------------

#ifndef MY_STACK

#define MY_STACK

#include<iostream>

#include<cstdlib>

#include<cstring>

#include<fstream>

using namespace std;

class Stack

{

    // declare stack array arr

    char *arr;

   

    // to store the index of the top most element

    int top;

   

    // to store the current capacity of arr

    int size;

   

    public:

       

        // constructor

        Stack();

       

        // constructor

        Stack(int);

       

        // destructor

        ~Stack();

       

        // function to check if the stack is empty

        bool isEmpty();

       

        // function to check if the stack is full

        bool isFull();

       

        // push element intot the stack

        void push(char);

       

        // return the top most element in the stack

        char peek();

       

        // pop element from stack

        void pop();

       

        // resize the array to double the original capacity

        void resize();

       

        // display contents of stack

        void view();

};

#endif


------------------Stack.cpp--------------------

#include "Stack.h"

// constructor

Stack::Stack()

{

    // declare an array of size 4

    arr = new char[4];

       

    // set initial capacity to 4

    size = 4;

       

    top = -1;

}

// constructor

Stack::Stack(int new_size)

{

    // declare an array of size new_size

    arr = new char[new_size];

       

    // set initial capacity to new_size

    this->size = new_size;

       

    top = -1;

}

// destructor

Stack::~Stack()

{

    delete arr;

    size = 0;

    top = -1;

}

// function to check if the stack is empty

bool Stack::isEmpty()

{

    if(top == -1)

        return true;

    return false;

}

// function to check if the stack is full

bool Stack::isFull()

{

    if(top == size - 1)

        return true;

    return false;

}

void Stack::push(char n)

{

    // if stack is full

    if(isFull())

        // resize the array to double the original capacity

        resize();

       

    arr[++top] = n;

}

// return the top most element in the stack

char Stack::peek()

{

   if(isEmpty())

        return -1;

       

    return arr[top];

}

// pop element from stack

void Stack::pop()

{

    // if stack is empty

    if(isEmpty())

        cout<<"The stack is alreasy empty";

   

    // remove the top most element of the stack

   top--;

}

// resize the array to double the original capacity

void Stack::resize()

{

    // create a new int array double the size of arr

    char *temp = new char[2 * size];

    int i;

   

    for( i = 0 ; i < size ; i++ )

        // cop contents of arr to temp

        temp[i] = arr[i];

   

    // set capacity to double the original capacity

    size *= 2;

   

    // set temp as the new stack array

    arr = temp;

}

// display contents of stack

void Stack::view()

{

    int i;

  

    for( i = 0 ; i <= top ; i++ )

        cout<<arr[i]<<" ";

       

    cout<<endl;

}


----------------------main.cpp--------------------

#include "Stack.cpp"

bool isInPair( char ch1 , char ch2 )

{

    return ( ch1 == '(' && ch2 == ')' ) || ( ch1 == '{' && ch2 == '}' ) || ( ch1 == '[' && ch2 == ']' );

}

bool isBalanced(string str)

{

    // create an object of type stack

    Stack ob;

   

    int i;

   

    for( i = 0 ; i < str.length() ; i++ )

    {

        // if the current bracket is opening bracket

        if(str[i] == '(' || str[i] == '{' || str[i] == '[')

            // push it into stack

            ob.push(str[i]);

        // if the current bracket is closing bracket

        else if( str[i] == ')' || str[i] == '}' || str[i] == ']' )

        {

            // check if stack is empty or not and the brackets on the top of stack and current character don't form a pair

            if(ob.isEmpty() || !isInPair( ob.peek() , str[i]) )

                return false;

            // check if stack is not empty or not and the brackets on the top of stack and current character form a pair

            else

                // remove top most element from stack

                ob.pop();

        }

    }

   

    // if stack is empty

    if( ob.isEmpty() )

        return true;

    else

        return false;

}

int main()

{

    cout<<"Enter file name : ";

    string fname, str;

   

    cin>>fname;

   

    // open file in read mode

    ifstream in(fname.c_str());

   

    // read complete line

    getline(in, str);

   

    if( isBalanced( str ) )

        cout<<"It is balanced.";

    else

        cout<<"it is not balanced.";

       

    return 0;

}

--------------------input.txt--------------------

{}(([][][[()(),|||'''"";;_-+= ]]))


Sample Output


Related Solutions

1. Write a program that prompts the user for a filename, then reads that file in...
1. Write a program that prompts the user for a filename, then reads that file in and displays the contents backwards, line by line, and character-by character on each line. You can do this with scalars, but an array is much easier to work with. If the original file is: abcdef ghijkl the output will be: lkjihg fedcba Need Help with this be done in only PERL. Please use "reverse"
Write a program that prompts the user to enter a file name, then opens the file...
Write a program that prompts the user to enter a file name, then opens the file in text mode and reads names. The file contains one name on each line. The program then compares each name with the name that is at the end of the file in a symmetrical position. For example if the file contains 10 names, the name #1 is compared with name #10, name #2 is compared with name #9, and so on. If you find...
Write a program that prompts the user for a file name, make sure the file exists...
Write a program that prompts the user for a file name, make sure the file exists and if it does reads through the file, count the number of times each word appears and then output the word count in a sorted order from high to low. The program should: Display a message stating its goal Prompt the user to enter a file name Check that the file can be opened and if not ask the user to try again (hint:...
Write a C program that Reads a text file(any file)  and writes it to a binary file....
Write a C program that Reads a text file(any file)  and writes it to a binary file. Reads the binary file and converts it to a text file.
Python program: Write a program that reads a text file named test_scores.txt to read the name...
Python program: Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for 3 tests. The program should display class average for first test (average of scores of test 1) and average (average of 3 tests) for each student. Expected Output: ['John', '25', '26', '27'] ['Michael', '24', '28', '29'] ['Adelle', '23', '24', '20'] [['John', '25', '26', '27'], ['Michael', '24', '28', '29'], ['Adelle', '23', '24', '20']] Class average for test 1...
C Programming Write a program in C that reads in a file, stores its contents as...
C Programming Write a program in C that reads in a file, stores its contents as a character array/pointer (char*) into an unsigned character array/pointer (unsigned char* message). Note: the input file can have one line or multiple lines and vary in length
Write a C++ program that reads a string from a text file and determines if the...
Write a C++ program that reads a string from a text file and determines if the string is a palindrome or not using stacks and queue
Write a C++ function that reads a .csv file(file contains rows of string(name) and number) into...
Write a C++ function that reads a .csv file(file contains rows of string(name) and number) into a vector and loop through that vector and find the max number.
Tail of a File, C++ Program. write a program that asks the user for the name...
Tail of a File, C++ Program. write a program that asks the user for the name of a text file. The program should display the last 10 lines, or all lines if less than 10. The program should do this using seekg Here is what I have so far. #include<iostream> #include<fstream> #include<string> using namespace std; class File { private:    fstream file;    string name; public:    int countlines();    void printlines(); }; int File::countlines() {    int total =...
Write a program in c that reads the content from the file and stores each line...
Write a program in c that reads the content from the file and stores each line in an int array in heap(using dynamic memory allocation). For example, let the file has elements following (we do not know the size of files, it could be above 100,000 and contents of the file and make sure to convert file elements to int): 10067 26789 6789 3467
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT