Hi everybody. I am writing a program that will take in values through inFile, all these values will be read as strings and converted to doubles. The range is 0.0 to 10.0, all values that cannot be converted will be written to a certain file "ReadErrors" and all values that are out of range will be written to "RangeErrors". To do this i am trying to implement exceptions.
The program is compiling and running even though it crashes after it has run to its end. Except the crash, the program only reads 700~ of my 20 000 values, and only finds 10 range errors even though there is around 200 of them.
#ifndef DataFileReader_H
#define DataFileReader_H
#include <string>
#include <iostream>
#include <fstream>
usingnamespace std;
template <typename T>
class DataFileReader {
private:
string dataFileName;
string errorFileName;
ifstream& dataFileStream;
ofstream& errorFileStream;
public:
DataFileReader(string aDataFileName, string aErrorFileName) : dataFileName(aDataFileName), errorFileName(aErrorFileName), dataFileStream(*(new std::ifstream(""))), errorFileStream(*(new std::ofstream(""))) {};
/* pre: A file named aDataFile contains values to read. */
~DataFileReader() { dataFileStream.close(); errorFileStream.close(); }
/* post: Files are closed */
void openFiles(); // throw (runtime_error);
/* post: An input stream from the file named aDataFile and an output stream to the file named aErrorFile are opened.
If either of these operations fails a runtime_error exception is thrown. */
bool readNextValue(T &aValue);
/* pre: openFiles has been successfully called.
post: If a value has been successfully read, aValue holds that value and true is returned.
Else, the read operation encountered an end-of-file and false is returned. */
};
#endif
#ifndef DataFilter_H
#define DataFilter_H
#include "DataFileReader.h"
template <typename T>
class DataFilter {
private:
DataFileReader<T> fileReader;
T min, max;
public:
DataFilter(DataFileReader<T> *aReader, T aMin, T aMax) : fileReader(*aReader), min(aMin), max(aMax) {};
/* pre: aReader points to an instance of DataFileReader<T> for which openFiles() has been succesfully called. */
bool getNextValue(T &aValue); // throw (range_error);
/* pre: an earlier call to getNextValue() has not returned false.
post: true is returned if aValue holds a value read from aReader. If a value could not be read, false is returned.
If a value is read but is not within the interval specified by aMin and aMax parameters to the constructor, a range_error exception is thrown. */
};
#endif
DataFilter.cpp
1 2 3 4 5 6 7 8 9 10 11
#include "DataFilter.h"
template <typename T>
bool DataFilter<T>::getNextValue(T &aValue) {
if (fileReader.readNextValue(aValue)) {
if (aValue > max || aValue < min)
throw(range_error("Outside of range"));
returntrue;
}
returnfalse;
}