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

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 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
Could you write a c- program that reads a text file into a linked list of...
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements 1. In paragraph 1 Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise 2. In pragraph 2 Replace "We" with v"i" This is the text to be manipulated: Paragraph1 She told us to take the trash out. Why did she do that? I wish she would...
Write a C++ program that reads a file consisting of students’ test scores in the range...
Write a C++ program that reads a file consisting of students’ test scores in the range 0–200. It should then determine the number of students having scores in each of the following ranges: 0–24, 25–49, 50–74, 75–99, 100–124, 125–149, 150–174, and 175–200. Output the score ranges and the number of students. (Run your program with the following input data: 76, 89, 150, 135, 200, 76, 12, 100, 150, 28, 178, 189, 167, 200, 175, 150, 87, 99, 129, 149, 176,...
C++ Write a program that reads candidate names and numbers of votes in from a file....
C++ Write a program that reads candidate names and numbers of votes in from a file. You may assume that each candidate has a single word first name and a single word last name (although you do not have to make this assumption). Your program should read the candidates and the number of votes received into one or more dynamically allocated arrays. In order to allocate the arrays you will need to know the number of records in the file....
Could you write a c- program that reads a text file into a linked list of...
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements 1. Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise 2. Replace "sh" with ph This is the text to be manipulated: Paragraph1 She told us to take the trash out. Why did she do that? I wish she would not do that Paragraph 2 We...
Write a parameterized function that takes in a file name as a parameter, reads the file,...
Write a parameterized function that takes in a file name as a parameter, reads the file, calculates the factorial of each number, and displays a formatted output as follows: Factorial of 10 = 3628800 Factorial of 5 = 120
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT