gpt4 book ai didi

c++ - strtok 字符串并修改 token 值

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

您好,我正在按照与以下示例类似的方式进行字符串标记化。但是,在 while 循环中,我会将字母“a”更改为“hellow”。在分配给 myVar[i] 之前尝试更改 pch 时出现段错误。我应该怎么做?

    map <int, char*> myVar;
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
int i = 0;

while (pch != NULL)
{
printf ("%s\n",pch);

//modify token value
stringstream strStream;
strStream << "hello_world";

char newStr[7] = {0};
memcpy(newStr, strStream, 7);

myVar[i] = (char*)newStr;
pch = strtok (NULL, " ,.-");
i++;
}

最佳答案

我在您的 while 循环中看到两个错误:

1) 您正在将 stringstream 本身而不是它包含的数据传递给 memcpy()。您依赖于 stringstream::operator void*() 转换运算符。您不应该尊重该指针,因为它不指向实际数据。它只是一个标志,指示 stringstream 是否有效。要将 stringstream 数据传递给 memcpy(),您必须先调用其 str() 方法以获取 std::string 包含数据,然后调用它的 c_str() 方法将该数据传递给 memcpy()

2) 当您将值插入到您的std::map 中时,您每次都会插入一个本地char[] 变量。 char[] 之后立即超出范围,留下 std::map 包含指向堆栈上随机位置的指针。鉴于您显示的代码,char[] 缓冲区很可能每次都重用相同的堆栈空间。

既然你在使用 C++,你真的应该使用更多面向 C++ 的东西,比如 std::stringstd::cout 等。

试试这个:

std::map <int, std::string> myVar;
std::string str = "- This, a sample string.";
std::cout << "Splitting string \"" << str << "\" into tokens:" << std::endl;
size_t start = 0;
int i = 0;

do
{
std::string token;

size_t pos = str.find_first_of(" ,.-", start);
if (pos != std::string::npos)
{
token = str.substr(start, pos-start);
start = pos + 1;
}
else
{
token = str.substr(start);
start = std::string::npos;
}

std::cout << token << std::endl;

//modify token value
myVar[i] = "hello_world";

++i;
}
while (start != std::string::npos);

关于c++ - strtok 字符串并修改 token 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13243116/

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