I have written this code which reads a file and stores it in a struct. and from struct it saves the data in a new file. The file name is inserted by the user and new file name is also generated dynamically.
But it is giving error.
HEAP CORRUPTION DETECTED: After Normal Block (#142) at 0x008620C8
CRT detected that the application wrote to memory after end of Heap buffer.
Here is my code
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
struct Data{
string ticker;
double date;
float open;
float high;
float low;
float close;
long volume;
};
int main()
{
Data data;
int i=0;
string name;
ifstream isf;
ofstream osf;
string sline;
char* cline = NULL;
char* chr = NULL;
char* jDate = NULL;
char* aChr = NULL;
char* d = NULL;
int day;
int month;
int year;
int intRes1;
int intRes2;
int intRes3;
//int jdn1;
int flag = 0;
long numlines = 0;
//int openFileCheck = 0;
string fileName;
cout << "Please enter a file name: \n";
cin >> name;
try{
isf.open(name.data());
while (! isf.eof() )
{
getline(isf,sline);
numlines++;
if(numlines == 1)
continue;
cline = new char[sline.length()+1];
strcpy(cline, sline.c_str());
chr = strtok(cline,",");
data.ticker +=string(chr);
fileName +=string(chr);
aChr = chr;
strcat(aChr, ".txt");
fileName =string(aChr);
osf.open(fileName.data());
osf<<data.ticker<<" ";
strcpy(cline, sline.c_str());
chr = strtok(cline,",");
while(chr != NULL && ! isf.eof()){
if(flag == 1){
data.ticker =string(chr);
osf<<data.ticker<<" ";
flag = 0;
}
chr = strtok(NULL,",");
if(i==0){
d= chr;
jDate = strtok(d,"/");
day = atoi(jDate);
jDate = strtok(NULL,"/");
month = atoi(jDate);
jDate = strtok(NULL,"/");
year = atoi(jDate);
intRes1 = ((2 - year / 100) + (year / 400));
intRes2 = int(365.25 * year);
intRes3 = int(30.6001 * (month + 1));
data.date = (intRes1 + intRes2 + intRes3 + day + 1720994.5);
osf<<data.date<<" ";
i++;
strcpy(cline, sline.c_str());
chr = strtok(cline, ",");
chr = strtok(NULL,",");
}
else if(i==1){
data.open = atof(chr);
osf<<data.open<<" ";
i++;
}
else if(i==2){
data.high = atof(chr);
osf<<data.high<<" ";
i++;
}
else if(i==3){
data.low = atof(chr);
osf<<data.low<<" ";
i++;
}
else if(i==4){
data.close = atof(chr);
osf<<data.close<<" ";
i++;
}
else if(i==5){
data.volume = atol(chr);
osf<<data.volume<<'\n';
flag = 1;
i = 0;
getline(isf,sline);
strcpy(cline, sline.c_str());
chr = strtok(cline,",");
}
}//end of while(chr != NULL)
osf.close();
}//end of while (! isf.eof() )
}//end of Try
catch(...){
cout<< "Can't find the file!\n";
}
delete [] cline;
delete chr;
delete d;
delete aChr;
delete jDate;
cin.clear();
cin.get();
return 0;
}