Stacks and balancing

I am using stacks to create a balancing program.
I would like the user to input the name of the file to be checked for balancing but when I enter a file name like "test.cpp", which exists and has code and is in the same directory, the program crashes.
It works if I type main.cpp or anything involving main such as main_2.cpp.

Any ideas why??

This is what I'm using.
1
2
3
4
5
6
7
8
    string file;
    cout << "Please enter the name of file with extension to check for balancing" << endl;
    cin >> file;
    ifstream infile(file);
    if (!infile){
        cout << "Unable to open file" << endl;
    return -1;
    }
closed account (28poGNh0)
Try to alter ifstream infile(file); with ifstream infile(file.c_str());
Last edited on
Tried that and still does not work. Tried using getline(file, in), does not work. Tried file.open(), does not work.
closed account (28poGNh0)
can you give me the whole code,also the data in the files you want to open
It seems to be some sort of segmentation fault on line 21. I'm testing normal cpp files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 #include <iostream>
#include <stack>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
    string fileName;
    cout << "Please enter the name of fileName with extension to check for balancing" << endl;
    cin >> fileName;
    ifstream infileName(fileName);

    string x;
    stack <int> mystack;
    while (getline(infileName, x)){
        for (int i=0; i<x.size(); i++){
            if ((x[i] == '(') || (x[i] == '[' ) || (x[i] == '{') || (x[i] == '/*'))
                mystack.push(x[i]);

			else if ((mystack.top() == '(' && x[i] == ')') || (mystack.top() == '[' && x[i] == ']') ||(mystack.top() == '{' && x[i] == '}') ||(mystack.top() == '/*' && x[i] == '*/'))
				mystack.pop();
			}
	}
    return 0;
}
closed account (28poGNh0)
I need the data in the files
It seems that anything in the textfile that is not within (), [] or {} provides the error
making a normal cpp file with this text added:

1
2
3
4
[
jelly
()
[


crashes the program
Last edited on
closed account (28poGNh0)
First : '(' , '[' and the others are one character unless '*/' and '/*'(those are two characters string)
that generates a warning .

second : about your for loop for (int i=0; i<x.size(); i++) ,you compare between a signed and unsigned interger ,which also generates a warning should be like this for (int size_t i=0; i<x.size(); i++)

finaly : I think the use of mystack.top() what makes the program crash
because in the second if ,you checking if mystack.top() == '(' ,even it is empty
Last edited on
Topic archived. No new replies allowed.