已解决:
您可以使用以下命令更改字符缓冲区:
char *arg;
arg = SCmd.next();
int i;
sscanf(arg, "%d", &i);
Serial.print("String value ");
Serial.println(arg);
Serial.print("Integer value ");
Serial.println(i);
问题:
我似乎不知道如何将char缓冲区的内容从存储的字符串更改为整数。
例如:
"1"应为1,
"121"应为121
这是我试过的。
void doIt()
{
char *arg;
arg = SCmd.next(); // Get the next argument from the SerialCommand object buffer
if (arg != NULL) // As long as it existed, do it
{
int argInted = (int)arg; // Cast char arg* -> int argInted.
Serial.print("String value ");
Serial.println(arg);
Serial.print("Integer value ");
Serial.println(argInted); // Print this new found integer.
}
else {
Serial.println("Fix your arguements");
}
}
这是我得到的,每次评估为371。不过,我在指针缓冲区中存储了不同的东西,有关于如何转换的想法吗?
Arduino Ready
> INPUT 1
String value 1
Integer value 371
> INPUT 2
String value 2
Integer value 371
> INPUT WHATSthisDO
String value WHATSthisDO
Integer value 371
引用WhozCraig:这不是将char*转换为int 的方法
简单的强制转换不起作用,因为char是1个字节,int是4个字节,所以剩下的3个字节可能包含任何垃圾,从而导致不可预测的结果:
char s[1] = {'2'};
cout << s << endl;
cout << (int)s << endl;
cout << atoi(s) << endl;
在我的机器上引导到
2
-5760069
2
要将char*
转换为int
,请使用atoi()
函数。http://www.cplusplus.com/reference/cstdlib/atoi/