我是 C 的新手,正在尝试拆分字符数组(我从 Ardunio 的串行端口接收到)。我查阅了一些教程并想出了这个。请帮我调试一下。
char action[10];
unsigned long duration;
void split(char input[20])
{
char *param, *ptr;
param = strtok_r(input, "#", &ptr);
action = *param; // Need help with this line
param = strtok_r(NULL, "!", &ptr);
duration = (unsigned long) *param; // Need help with this line
}
据我了解,strtok_r 返回指向分隔符 (#) 之后的字符的指针。那么,如果我想让 action[] 成为 input[] 的子集字符数组,直到分隔符,我应该怎么做?
编辑: 输入是这样的:“left#1000!”
最佳答案
看起来您的第一个标记是字符串,第二个标记是长整数。您可以使用 strncpy
将param
复制到action
中,然后strtoul
将 unsigned long
解析为 duration
。
param = strtok_r(input, "#!", &ptr);
strncpy(action, param, sizeof(action));
// Force zero termination
action[sizeof(action)-1] = '\0';
param = strtok_r(NULL, "#!", ptr);
duration = strtoul(param, ¶m, 10);
关于困惑 : Pointers and character arrays in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11505165/