fstream

I am writing a program that turns infix expressions into postfix. And I have to either output to a file provide or output to the screen. The is the program.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  #include "stack.hpp"
#include <iostream>
#include <fstream>

String Topostfix(std::istream&);

int main(int argc, char *argv[]){


  std::ifstream in(argv[1]) ;
  if(!in)
    {std::cerr<<"Couldn't open "<<argv[2] << "\n" ;}

  String b ;


  if(argc !=3){
    while(in>>b){
      std::cout<<"postfix = "<<Topostfix(in)<<std::endl<<std::endl;
    }
  }

  else{
    std::ofstream outputfile(argv[2]) ;
    while(in>>b){
      outputfile<<"postfix = "<<Topostfix(in)<<std::endl<<std::endl;
    }
  }

  in.close();
  return 0;

}

//Takes the file for parameter then reads in and converts each line to postfix while printing out the infix  
//Pre: valid input (fully parenthesized and spaces inbetween the characters.
//Post: Printed out the infix spaced and returns the postfix which was the tos.
String Topostfix(std::istream& in){

  stack<String> result ;
  String right,op,left ;
  String cin ;
  std::cout<<"infix = (" ;
  while(cin != ';'){
    if(cin ==')'){
      right = result.pop() ;
      op = result.pop() ;
      left = result.pop() ;
      result.push(left+" "+right+" "+op);
    }

    else if(cin !='(')
      result.push(cin) ;

    std::cout<<cin<<" " ;
    in>>cin;
  }

  outputfile<<std::endl;
  return result.gettos() -> data ;
}



Now the problem is in the function Topostfix if there was an outputfile given I need to print to it and I was just wondering how to do this rather then just printing to the screen.
Last edited on
Topic archived. No new replies allowed.