I have a class with an inner class which has a member ifstream. When executing the code throws an AccessViolationException in TestDataHelper::getNextLine()
at if(!datafile->eof())
.
Debugging showed me that the constructor is working fine. The file is created and the first line is read. But when I check the datafile after the assignment is done (after TestDataHelper helper = TestDataHelper("data.csv");
), the datafile becomes an invalid pointer.
The code:
IfstreamTester.h
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
class IfstreamTester
{
public:
IfstreamTester(void);
~IfstreamTester(void);
void doStuff();
private:
std::ifstream file;
class TestDataHelper{
private:
std::ifstream *datafile;
public:
TestDataHelper(std::string filename);
~TestDataHelper();
std::vector<double>* getNextLine();
};
};
IfstreamTester.cpp
#include "IfstreamTester.h"
using namespace std;
IfstreamTester::IfstreamTester(void)
{}
IfstreamTester::~IfstreamTester(void)
{}
void IfstreamTester::doStuff()
{
TestDataHelper helper = TestDataHelper("data.csv");
// for every line in the file
vector<double>* v;
do
{
v = helper.getNextLine();
cout << v << endl;
delete v;
} while(v != NULL);
}
IfstreamTester::TestDataHelper::TestDataHelper(std::string filename)
{
datafile = new ifstream(filename.c_str());
// read the header line
string line;
getline(*datafile, line);
}
vector<double>* IfstreamTester::TestDataHelper::getNextLine()
{
if(!datafile->eof())
{
// readline
string line = "";
getline(*datafile, line);
string delimiter = ",";
vector<double>* res = new vector<double>();
size_t pos = 0;
// and tokenize line into vector of doubles
while ((pos = line.find(delimiter)) != std::string::npos)
{
stringstream conv;
double token;
conv << line.substr(0, pos);
conv >> token;
res->push_back(token);
line.erase(0, pos + delimiter.length());
}
return res;
}
else
{
return NULL;
}
}
IfstreamTester::TestDataHelper::~TestDataHelper()
{
datafile->close();
delete datafile;
}
and the main:
#include "IfstreamTester.h"
void main()
{
IfstreamTester s = IfstreamTester();
s.doStuff();
}
Anyone an idea why this is so?
EDIT: I am using Microsoft Visual Studio 2008 Express