Question

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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include<bits/stdc++.h>
using namespace std;
  
// function to check if paranthesis are balanced
bool areParanthesisBalanced(string expr)
{
stack<char> s;
char x;
  
// Traversing the Expression
for (int i=0; i<expr.length(); i++)
{
if (expr[i]=='('||expr[i]=='['||expr[i]=='{')
{
// Push the element in the stack
s.push(expr[i]);
continue;
}
  
// IF current current character is not opening
// bracket, then it must be closing. So stack
// cannot be empty at this point.
if (s.empty())
return false;
  
switch (expr[i])
{
case ')':
  
// Store the top element in a
x = s.top();
s.pop();
if (x=='{' || x=='[')
return false;
break;
  
case '}':
  
// Store the top element in b
x = s.top();
s.pop();
if (x=='(' || x=='[')
return false;
break;
  
case ']':
  
// Store the top element in c
x = s.top();
s.pop();
if (x =='(' || x == '{')
return false;
break;
}
}
  
// Check Empty Stack
return (s.empty());
}
  
// Driver program to test above function
int main()
{
cout<<"Enter the file name\n";
char filename[20];
cin>>filename;

ifstream file; //using input stream to read the contents of the file
file.open(filename);

char ch;
string s="";
while (file >> ch) { //reading the content from file char by char
s=s+ch;                       //storing the content in the string s      
}

if (areParanthesisBalanced(s))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}

Add a comment
Know the answer?
Add Answer to:
C++ Write a program that prompts for a file name and then reads the file to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program that takes a file as input and checks whether or not the content...

    Write a program that takes a file as input and checks whether or not the content of the file is balanced. In the context of this assignment “balanced” means that your program will check to make sure that for each left bracket there is a closing right bracket. Examples:             [ ( ) ] { } à balanced.             [ ( ] ) { } à unbalanced. Here is the list of brackets/braces that program must support: (: left parentheses...

  • Use PYTHON Write a program that will take an input file called input.txt which will contain a Jav...

    use PYTHON Write a program that will take an input file called input.txt which will contain a Java program and parse it and output an annotated version. Your program will track the nesting depth of the braces of the input file and will output an annotated version of the file. Your final program will 1. List the nesting depth of curly braces 2. Ignore braces inside quotes or comments Use Python Assume that all quoted strings begin and end on...

  • 7.2 Write a program that prompts for a file name, then opens that file and reads...

    7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: X-DSPAM-Confidence: 0.8475 Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution. You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are...

  • Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains...

    Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains a Java program. Your program should read the file (e.g., InputFile.java) and output its contents properly indented to ProgramName_Formatted.java (e.g., InputFile_Formatted.java). (Note: It will be up to the user to change the name appropriately for compilation later.) When you see a left-brace character ({) in the file, increase your indentation level by NUM_SPACES spaces. When you see a right-brace character (}), decrease your indentation...

  • Write a program that prompts the user for a String value and a character value. The...

    Write a program that prompts the user for a String value and a character value. The program should then find the last occurrence of the provided character in the provided String and display the corresponding index. If the character is not found in the String, display -1. For additional challenge, create a multi-class solution. The business class should consist of two instance varaibles to store the user provided values and one method to accomplish the given task. The tester class...

  • C Programming QUESTION 9 Write a program that prompts for and reads four integer input values,...

    C Programming QUESTION 9 Write a program that prompts for and reads four integer input values, then a single character command. Submit your program as a .c file named midterm_prog2.c. Note that, similarly to your programming assignments, some percentage of your grade will depend on proper programming style. Your program will calculate and print a new value based on the command that's entered, as follows: 'A' or 'a': Calculate the average of the four input values 'S' or 's': Calculate...

  • C++ Here, we want to enforce proper delimiter rules in a string. For example, if a...

    C++ Here, we want to enforce proper delimiter rules in a string. For example, if a user types something like this at the console: "This is my string, and it is properly delimited: 1*((3 + 4)*8)". Notice how the open parentheses are properly matching with closed parenthesis. We want to enable a user to create a string using more than one type of delimiter to bracket information into "blocks." For example, A string may use braces {}, parentheses (), and...

  • Write a Python program which prompts the user for a file name then a sentence. Display...

    Write a Python program which prompts the user for a file name then a sentence. Display the number of characters in the sentence and save the sentence to the file name. If the file already exists, ask the user if the file should be overwritten.

  • In C++, write a program that reads a postfix expression from an input file. Then, the...

    In C++, write a program that reads a postfix expression from an input file. Then, the program should evaluate the postfix format and display the results. Use these concepts for the program: 1) Struct Node 2) Enqueue and Dequeue 3) Push and Pop 4) DO NOT USE classes 5) Possibly Stack Precondition: The expression will be read from a file (input.txt) that contains a single line. There will be no spaces between the operands and the operators. The following operators...

  • write a C++ program that reads in a text file and reads each character or lexemes...

    write a C++ program that reads in a text file and reads each character or lexemes and states what token it is and writes to another file for example: while (fahr < upper) a = 23.00 whileend Output: token lexeme -------------------------------- keyword while separator ( identifier fahr operator < identifier upper separator ) identifier a operator = real 23.00 keyword whileend the program aslo reads in comments but does not add to the list. characters that are commented out or...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT