我想将 a 转换String
为 an int
,我能找到的只是您必须将 String 转换为 char 数组,然后将此数组转换为 an int
,但是我的代码会产生奇怪的值,我无法弄清楚问题出在哪里.
void ledDimm(String command)
{
// Get the Value xx from string LEDDimm=xx
String substring = command.substring(8, command.length());
Serial.println("SubString:");
Serial.println(substring);
Serial.println("SubString Length:");
Serial.println(substring.length());
// Create a Char Array to Store the Substring for conversion
char valueArray[substring.length() + 1];
Serial.println("sizeof ValueArray");
Serial.println(sizeof(valueArray));
// Copy the substring into the array
substring.toCharArray(valueArray, sizeof(valueArray));
Serial.println("valueArray:");
Serial.println(valueArray);
// Convert char array to an int value
int value = int(valueArray);
Serial.println("Integer Value:");
Serial.println(value);
// Write the Value to the LEDPin
analogWrite(LEDPin, value);
}
串行输出如下所示:
Received packet of size 11
From 192.168.1.4, port 58615
Contents:
LEDDimm=100
SubString:
100
SubString Length:
3
sizeof ValueArray
4
valueArray:
100
Integer Value:
2225
我希望得到一个值为 100 的 int,但实际的 int 是 2225?!我在这里做错了什么?