Hi I am trying to make a simple reading from a text file. I need to split the strings hence I use strtok. However when I use char* as the strings, it just shows me an error.
Below is my code. Any advise?
void encrypt(fstream& afile,char* fileName,int size){
string txt,tmp;
int key[100][100],num,n=0,m=0;
afile.open(fileName,ios::in);
while (afile>>tmp)
{
txt = txt + tmp;
}
afile.close();
afile.open("keyfile.txt",ios::in);
char *pch = new char(100),*tmp2 = new char(100);
while (afile>>tmp2)
{
pch = strtok (tmp2,";");
while (pch != NULL)
{
key[n][m] = atoi(pch);
cout<<key[n][m]<<" ";
pch = strtok (NULL, ";");
m++;
}
cout<<endl;
n++;
}
delete []tmp2;
delete []pch;
afile.close();
}
This allocates a single char for both pch
and tmp2
, and sets that value to 100:
char *pch = new char(100),*tmp2 = new char(100);
What you want is this:
char *pch = new char[100];
char *tmp2 = new char[100];
But there is a memory leak, since you replace pch
immediately with the return value of strtok
. So there is no need to allocate for pch
.
In addition, you could have just declared an array of 100 chars for tmp2
instead of dynamically allocating:
char tmp2[100];
So it all boils down to this:
char *pch;
char tmp2[100];
with no need for delete[]
at the end of the function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.