ifstream as a member function

any idea why it doesn't work to call ifstream from a separate class and then manipulate the file within the class its called from?
ex:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void symbol::openFile()
{
    std::ifstream myfile ("info.csv");
}

void symbol::parseCSV(int *ptr)
{
    openFile();
    std::string data;
    
    while(myfile.good())
    {
            getline(myfile, data, ',');
            *ptr=data;
            *ptr++;
    }
myfile I take it wasn't declared in a class-wide scope in symbol. You'll need to do that, else myfile is limited to symbol::openFile().

-Albatross
Something called "scope".

you define std::ifstream myfile; in the function void symbol::openFile(). So its 'scope' is limited to that function. When that function returns, your variable myfile is destroyed.

If you want a variable to persist between member function calls you need to give them 'class scope' rather than 'function scope'.

You need to define them in your class declaration rather than in the function definition:

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
class symbol
{
private:
    std::ifstream myfile; // define it here

public:
    void openFile();
    void parseCSV(int* ptr);
};

void symbol::openFile()
{
    myfile.open("info.csv"); // open it here
}

void symbol::parseCSV(int *ptr)
{
    openFile();
    std::string data;
    
    while(myfile.good()) // use it here also
    {
            getline(myfile, data, ',');
            *ptr=data;
            *ptr++;
    }
}
You can do that, the only problem above is that you are creating a local variable myfile that is destroyed when it goes out of scope.

If only I didn't take that last call... ;)
Last edited on
Good deal. Thanks.
Topic archived. No new replies allowed.