Im trying to create a c program that checks to see if a give

Im trying to create a c++ program that checks to see if a given file is balanced but the code constantly says it is balanced when it is not, code:

#include <iostream>
#include <fstream>
#include <stack>
#include <string>

using namespace std;

int main()
{
ifstream infile;
char f[100];

cout << \"Enter the name of the file you wish to open.\" << endl;
cin >> f;
infile.open(f);

//cout << f << endl;

if (infile.fail())
{
  cout << \"Cannot find file.\" << endl;
}
else
{
  char c;
  stack <char> stack;
  int x = 0;
  while (infile >> c)
   cout << c << endl; // Delete this
  {
   if (c == \'(\' || c == \'{\' || c == \'[\')
   {
    stack.push(c);
   }
   if (!stack.empty() && (c == \')\' || c == \'}\' || c == \']\'))
   {
   if( (stack.top() == \'(\' && c == \')\' ) || (stack.top() == \'{\' && c == \'}\' ) || (stack.top() == \'[\' && c ==\']\'))
    {
     stack.pop();
    }
    else
    {
     x == 1;
    }
   }
   
  }
  if (stack.empty() && x == 0)
  {
   cout << \"File is balanced.\" << endl;
  }
  else
  {
   cout << \"File is not balanced.\" << endl;
  }

  {
   int z = 0;
   cin >> z;
  }
}

}

Solution

#include <iostream>
#include <fstream>
#include <stack>
#include <string>

using namespace std;

int main()
{
ifstream infile;
char f[100];

cout << \"Enter the name of the file you wish to open.\" << endl;
cin >> f;
infile.open(f);

cout << f << endl;

if (infile.fail())
{
  cout << \"Cannot find file.\" << endl;
}
else
{
  char c;
  stack <char> stack;
  int x = 0;
  while (infile >> c)
   cout << c << endl; // Delete this
  {
   if (c == \'(\' || c == \'{\' || c == \'[\')
   {
    stack.push(c);
   }
   if (!stack.empty() && (c == \')\' || c == \'}\' || c == \']\'))
   {
if( (stack.top() == \'(\' && c == \')\' ) || (stack.top() == \'{\' && c == \'}\' ) || (stack.top() == \'[\' && c ==\']\'))
    {
     stack.pop();
    }
    else
    {
     x == 1;
    }
   }
   
  }
  if (stack.empty() && x == 0)
  {
   cout << \"File is balanced.\" << endl;
  }
  else
  {
   cout << \"File is not balanced.\" << endl;

   int z = 0;
   cin >> z;
  }
}

}

Im trying to create a c++ program that checks to see if a given file is balanced but the code constantly says it is balanced when it is not, code: #include <
Im trying to create a c++ program that checks to see if a given file is balanced but the code constantly says it is balanced when it is not, code: #include <
Im trying to create a c++ program that checks to see if a given file is balanced but the code constantly says it is balanced when it is not, code: #include <

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site