gpt4 book ai didi

C++ char * split with strtok 不工作

转载 作者:行者123 更新时间:2023-11-28 06:37:28 24 4
gpt4 key购买 nike

您好,我正在尝试从文本文件中进行简单的读取。我需要拆分字符串,因此我使用 strtok。然而,当我使用 char* 作为字符串时,它只显示错误。

下面是我的代码。有什么建议吗?

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();
}

最佳答案

这为 pchtmp2 分配了一个字符,并将该值设置为 100:

char *pch = new char(100),*tmp2 = new char(100);

你要的是这个:

char *pch = new char[100];
char *tmp2 = new char[100];

但是存在内存泄漏,因为您立即将 pch 替换为 strtok 的返回值。所以不需要为pch分配。

此外,您可以为 tmp2 声明一个包含 100 个字符的数组,而不是动态分配:

char tmp2[100];

所以这一切都归结为:

char *pch;
char tmp2[100];

函数末尾不需要 delete[]

关于C++ char * split with strtok 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26568826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com