const char * 中的不可见字符作为 strtok() 分隔符
我必须通过“新行”或“换行”字符(dec 10,十六进制 0x0A)分割网络数据的有效负载。 所以我尝试使用 strtok() 函数,但遇到了几个问题 当我想用“换行”字符创建一个 const char 字符串时。
原型:
`strtok(char * StringToSplit, const char * Delimiters)`
这导致了一个无效的初始值设定项:
`const char delim[] = 10;`
这给出了关于在不进行强制转换的情况下从 int 生成指针的警告; 虽然printf("Delim: %x", delim)
显示正确的 delim 值 (0xa) 在 strtok() 中使用时应用程序崩溃。
`const char * delim = 10;`
没有警告或错误, printf("Delim: %x", delim) 给出了正确的值 但 strtok() 不起作用(尽管如我所料)。
`char delim = 10;` `(ofc strtok(..., &delim))`
这似乎完成了工作,但我仍然收到关于传递非 const char ptr 的警告,其中 const char ptr 预计为 strtok() 函数。
`char delim[] = "#";` `delim[0] = 10;`
最后,这似乎可以在没有警告的情况下工作。
`char tmp[] = "#";` `tmp[0] = 10;` `const char *delim = tmp;`
问题是,将这样一个不可见字符传递给 strtok() 函数的最简单、最优雅的方法是什么? 对我来说,感觉这只是拼凑的代码。
I had to split the payload of network data by the "new line" or "line feed" character (dec 10, hex 0x0A).
So i tried to use strtok() function with which i encountered several problems
when i wanted to make a const char string with the "new line" character.
Proto:
`strtok(char * StringToSplit, const char * Delimiters)`
This made an invalid initializer:
`const char delim[] = 10;`
This gave warning about making pointer from int without cast;
Allthoughprintf("Delim: %x", delim)
showed correct value of delim (0xa)
the app crashes when used in strtok().
`const char * delim = 10;`
No warning or errors, printf("Delim: %x", delim) gave correct value
but strtok() didn't work (as i expected, though).
`char delim = 10;` `(ofc strtok(..., &delim))`
This seemed to do the job but i still got a warning about passing a non const char ptr where a const char ptr was expected to strtok() function.
`char delim[] = "#";` `delim[0] = 10;`
Finally this seems to work without warnings.
`char tmp[] = "#";` `tmp[0] = 10;` `const char *delim = tmp;`
Question is, what would be the simplest and most elegant way to pass such a non-visible character to the strtok() function?
To me it feels like this is just kludged code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要:
第二个参数必须是包含分隔符的 C 字符串。在您的各种化身中,有很多东西不是 C 字符串被错误地转换为 C 字符串。
You need:
The second parameter needs to be a C string containing the delimiters. What you have in your various incarnations are lots of things that aren't C strings being incorrectly cast to C strings.
它并不是拼凑或不雅,只是有很多错误。
为什么要在这里声明一个数组?这应该是:
然后:
为什么要声明一个数组并将其设置为等于字符串?这应该是:
It's not kludged or inelegant, it's just got lots of bugs.
Why are you declaring an array here? This should be:
And then:
Why are you declaring an array and setting it equal to a string? This shuld be: