I am trying use the content of a file as input and separate operands, parenthesis and operators. Since the input file contains 2 lines of input, I thought I should read the whole line instead of a value at a time because I do not want to mix up the values from the two lines. What I was thinking of doing is
- Using getline and store one line at a time into a string variable called input
- Break down the string (using white space as delimiter) into segments and push them into a stack called tempContainer.
- Store tempContainer.top() into a temp variable and call tempContainer.pop()
- Process temp to separate parenthesis from operand and store them into two different variables.
Everything went well till I try pushing the last data into the stack. I checked the values before calling tempContainer.push(temp); and everything checks out fine, so I don't get why I am getting a segmentation fault. The error occur during runtime, not during compilation.
Output produced:
A + B * (C - D * E) / F    <-----The original line to break down. Line 1
A
+
B
*
(C
-
D
*
E)
/
F
AB * CDE + (RST - UV / XX) * 3 - X5  <-----Line 2
AB
*
CDE
+
(RST
-
UV
/
XX)
*
3
-
//Segmentation fault here
Here's the code (the line with the error is near the bottom)
int main(int argc, char* argv[])
{
   string input, temp;
   fstream fin;
   stack<string>aStack;
   vector<string>sOutput;
   stack<string>tempContainer;
   int substr1, substr2;
   fin.open(argv[1], ios::in);
   if(!fin.good())
   {
      //...
   }
   else
   {
      while(!fin.eof())
      {
         getline(fin, input);
         cout << input << endl; //For verifying the content of input. Delete later
         if(input[0] == '\0')  //To prevent reading the last data in a file twice
         {
            break;
         } 
         else
         {
            //+++++++++++++++++++Breaking down string into sections++++++++++++++++++++
            //Storing the unprocessed segments of the original string into a stack
            //segments will be popped out later to be processed to separate parenthesis
            substr1 = 0;
            substr2 = 0;
            for(int i = 0; i < input.length(); )
            {
                while(input[i] != ' ')
                {
                   substr2++;
                   i++;
                }
                temp = input.substr(substr1, substr2 - substr1);
                substr2++;
                substr1 = substr2;
                i++;
                tempContainer.push(temp);  //ERROR here
                cout << tempContainer.top() << endl; //For testing purpose, delete later.
            }
            //+++++++++++++++++++++Finish breaking down strings++++++++++++++++++++++
         }
      }
   }
}
Could you help me track down the error(s)? Thank you for your time!
 
    