How do you convert a String to a float or int?
In an Arduino program I'm working on the GPS sends the coordinates to the arduino through USB. Because of this, the incoming coordinates are stored as Strings. Is there any way to convert the GPS coordinates to a float or int?
I've tried int gpslong = atoi(curLongitude)
and float gpslong = atof(curLongitude)
, but they both cause Arduino to give an error:
error: cannot convert 'String' to 'const char*' for argument '1' to 'int atoi(const char*)'
Does anyone have any suggestions?
You can get an int
from a String
by just calling toInt
on the String
object (eg curLongitude.toInt()
).
If you want a float
, you can use atof
in conjunction with the toCharArray
method:
char floatbuf[32]; // make this at least big enough for the whole string
curLongitude.toCharArray(floatbuf, sizeof(floatbuf));
float f = atof(floatbuf);
c_str()
will give you the string buffer const char* pointer.
.
So you can use your convertion functions:.
int gpslong = atoi(curLongitude.c_str())
float gpslong = atof(curLongitude.c_str())
How about sscanf(curLongitude, "%i", &gpslong)
or sscanf(curLongitude, "%f", &gpslong)
? Depending on how the strings look, you might have to modify the format string, of course.
上一篇: 奇怪的Arduino行为与跳线
下一篇: 如何将字符串转换为float或int?