C 和 Arduino 编程的新手,我的问题,如何将 char c 拆分为两个单独的整数变量? char c 的值看起来像这样 140,100
,两个数字都是整数。我需要根据这些数据创建两个整数变量 SpeedX
和 SpeedY
以便 SpeedX = 140
和 SpeedY = 100
。感谢您的帮助!
最佳答案
how to split char c into two separate integer variables?
- 首先,您拥有的是一个字符串,而不是一个
char
。 您可以使用
strtok()
函数拆分字符串(并指定要使用的分隔符),如下所示:#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char nums[] = "140,100"; char *str; int num; int SpeedX, SpeedY, i = 0; str = strtok (nums, ","); while (str != NULL) { num = atoi(str); if (i == 0) SpeedX = num; else if (i == 1) SpeedY = num; str = strtok (NULL, ","); i++; } return 0; }
注意:如果,一般来说这样的问题要在c中解决而不是 arduino ,您不确定
nums
中只有两个元素,您应该使用动态内存分配(阅读更多相关信息 here),并像这样修改您的代码:#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char nums[] = "140,100,500"; char *str; int num; int len, i = 0; int *p; str = strtok (nums, ","); len = strlen(str); p = malloc((len-1)*sizeof(int)); while (str != NULL) { num = atoi(str); *(p+i) = num; i++; str = strtok (NULL, ","); } for (i = 0; i < len-1; i++) printf("%d\n", *(p+i)); return 0; }
关于c - 分隔字符中的两个值并将它们分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41868245/