// filesdemo.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include #include using namespace std; const char* sourcefile = "f:\\Temp\\input.txt"; class Numbers { int n, k; int *data; int cstart, cend; bool isloaded; public: Numbers(); Numbers(const char*); void printRange(ostream& , const int , const int ) const; void printData(ostream& ) const; void printFound(ostream& ) const; bool loadData(istream& ); bool loadFile(const char* ); bool getNext(); }; ostream& operator <<= (ostream& ostr, Numbers& num) { num.printFound(ostr); return ostr; } Numbers::Numbers() : cstart(-1), cend(-1) { } Numbers::Numbers(const char* fname) : cstart(-1), cend(-1) { isloaded = loadFile(fname); } bool Numbers::loadFile(const char* name) { ifstream ifs(name); if (!ifs) { // check if file was open cout << " failed opening file " << endl; return false; } return loadData(ifs); } void Numbers::printRange(ostream& ostr, const int from, const int to) const { ostr << "[" << from << "," << to << "] : "; for (int i=from; i> n; ifs >> k; // allocate memory data = new int[n]; // read integer values until EndOfFile is encountered // or feasible (n) number of values is retrieved while (! ifs.eof() && i < n) { ifs >> data[i++]; } // have we read enough numbers if (i != n) return false; return true; } bool Numbers::getNext() { cstart++; int sum = 0; cend = cstart; while (cend < n) { if (data[cend] > k) { cstart = ++cend; sum = 0; continue; } // while the current sum would overflow k // when adding data[cend] - remove it while (sum + data[cend] > k) { sum -= data[cstart++]; } // return true if match found if (sum + data[cend] == k) { return true; } sum += data[cend++]; } return false; } int main() { Numbers nums(sourcefile); ofstream ofs("f:\\temp\\more.results.txt"); while (nums.getNext()) { cout <<= nums; ofs <<= nums; }; }