Reading in data from a file one line at a time

Hello all I am trying to read in expressions from a file and print them out in postfix. I can't seem to figure out how to make it read one line print out the expression in postfix and then read in the next line. For some reason it reads in all the data then prints out that in postfix.
Here is what is the the file:
2 + 3 * 5
2 + 3 * 5 ^ 6
Here is what it is printing:
2352*+356^*+


#include <fstream>
#include <iostream>
#include <sstream>
#include <stack>
#include <string>
using namespace std;

int priority(char a)
{
int temp;
if (a == '^')
temp = 3;
else if (a == '*' || a == '/')
temp = 2;
else if (a == '+' || a == '-')
temp = 1;
return temp;
}

int main()
{
string aline;
ifstream indata;
indata.open("infix.data");

stack<char> ostack;

stringstream output;
while(getline(indata,aline))
{
for (int i = 0; i < aline.length(); i++)
{
if(aline[i] == ' ')
i++;
if (aline[i] == '+' || aline[i] == '-' || aline[i] == '*' || aline[i] == '/' || aline[i] == '^')
{
while (!ostack.empty() && priority(ostack.top()) >= priority(aline[i]))
{
output << ostack.top();
ostack.pop();
}
ostack.push(aline[i]);
}
else if (aline[i] == '(')
{
ostack.push(aline[i]);
}
else if (aline[i] == ')')
{
while (ostack.top() != '(')
{
output << ostack.top();
ostack.pop();
}
ostack.pop();
}
else
{
output << aline[i];
}
}
}
indata.close();
while (!ostack.empty())
{
output << ostack.top();
ostack.pop();
}

cout<<aline<<endl;
cout << output.str() << endl;


}


Your program does read input from the file one line at a time.
However, you wait until reaching the end of the file before generating any output.

You need to move these lines:
1
2
3
4
5
6
7
8
        while (!ostack.empty())
        {
            output << ostack.top();
            ostack.pop();
        }

        cout << aline << endl;
        cout << output.str() << endl;

so that they are inside the while-getline loop, just before the closing brace of that loop.

Also, you need to clear the contents of the stringstream so that it is empty at the start of each pass through the loop:
output.str(""); // empty the stringstream

Also, please enclose your code in tags [code]your code here[/code]. The formatting button <> on the right hand side will add the tags for you.
It works! Thank you for your help. I will definitely use the tags in the future.
Topic archived. No new replies allowed.