read a new line from file multiple function calls

I'm trying to read in a file one line at a time inside a function that gets called multiple times from main, but I cant seem to get it to stop at the end of a line, or maintain its position in the file between calls. Is there a way to get the file read to maintain its index after the function ends and get it to read in only one line?

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
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;

#include "StackType.h"


// function prototypes
void infixIn(StackType<char> *);

int main(int argc, char *argv[])
{
    StackType<char> infix(256);
    
    
    infixIn(&infix);
    while(!infix.isEmpty())
        cout << infix.pop();

    infixIn(&infix);
    while(!infix.isEmpty())
        cout << infix.pop();        
        
    system("PAUSE");
    return EXIT_SUCCESS;
}

void infixIn(StackType<char> *infix)
{    
    char in;
         
    // opens infix.txt file
    ifstream inFile;    
    if(!inFile.is_open());
       inFile.open("infix.txt");
    
    // checks to see if the file opened correctly    
    if (!inFile)
       cout << "Error opening file\n";
    else
    {
        // reads in 1 line and stores the elements in the infix stack
        while (inFile >> in && in != '\n')
       {
           infix->push(in);
       }    
        // closes the file
        //inFile.close();       
    } 

}


infix.txt
1
2
3
4
5
((A+B)-C)/(C+B)
(A*B)-C*D
(C-(B+A))*A-B
(A+B*(C-D))/E
A+B*C/D-E
Last edited on
Here are three options:

1. Declare inFile as static. This ensures that it always has the same address and isn't destroyed when the function ends. The file will remain open between function calls;
static ifstream inFile;

2. Make infixIn a member function of <template T> class StackType; and make ifstream inFile an object in the class.

3. Open inFile in main and pass it as a reference to the infixIn function:
1
2
3
4
5
6
7
8
9
int main()
{
    ifstream inFile("infix.txt");
    infixIn(&infix, inFile);
}

void infixIn(StackType<char> *infix, ifstream &inFile) // Using pass-by-reference instead of pass-by-pointer.
{
}
Last edited on
thanks. I opened it in main and it persists between function calls, but I still cant get it to stop at the end of a line. I thought while (inFile >> in && in != '\n') would stop at the end of each line, but it reads in the whole file and stores it in the stack.

nevermind, I used getline with a string then walked through the string to separate the characters
Last edited on
Topic archived. No new replies allowed.