gpt4 book ai didi

c++ - C++中的Strtok异常行为

转载 作者:太空狗 更新时间:2023-10-29 19:57:09 25 4
gpt4 key购买 nike

我正在尝试在 C++ 中使用 strtok 来获取字符串的标记。但是,我看到在 5 次运行中的一次中,函数返回的标记不正确。有人可以建议可能是什么问题吗?

重现我面临的问题的示例代码:

#include<iostream>
#include<vector>
#include<cstring>

using namespace std;
#define DEBUG(x) cout<<x<<endl;


void split(const string &s, const char* delim, vector<string> & v)
{
DEBUG("Input string to split:"<<s);

// to avoid modifying original string first duplicate the original string and return a char pointer then free the memory
char * dup = strdup(s.c_str());
DEBUG("dup is:"<<dup);
int i=0;
char* token = strtok(dup,delim);

while(token != NULL)
{
DEBUG("token is:"<<string(token));
v.push_back(string(token));
// the call is treated as a subsequent calls to strtok:
// the function continues from where it left in previous invocation
token = strtok(NULL,delim);
}
free(dup);
}

int main()
{
string a ="MOVC R1,R1,#434";

vector<string> tokens;
char delims[] = {' ',','};
split(a,delims,tokens);
return 0;
}

示例输出:

mayank@Mayank:~/Documents/practice$ ./a.out 
Input string to split:MOVC R1,R1,#434
dup is:MOVC R1,R1,#434
token is:MOVC
token is:R1
token is:R1
token is:#434

mayank@Mayank:~/Documents/practice$ ./a.out
Input string to split:MOVC R1,R1,#434
dup is:MOVC R1,R1,#434
token is:MO
token is:C
token is:R1
token is:R1
token is:#434

正如您在第二次运行中看到的那样,创建的 token 是 MO C R1 R1 #434 而不是 MOVC R1 R1 #434

我也尝试检查库代码,但无法找出错误。请帮忙。

EDIT1:我的 gcc 版本是:gcc version 6.2.0 20161005 (Ubuntu 6.2.0-5ubuntu12)

最佳答案

char delims[] = {' ',','};

应该是

char delims[] = " ,";

您传递的是一个字符列表,而不是包含要使用的分隔符列表的 char *,因此出现意外行为,因为 strtok 需要一个以 0 结尾的字符串。在您的情况下,strtok 进入“林中”并用声明的数组之后的任何内容进行标记化。

关于c++ - C++中的Strtok异常行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40332568/

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