Arduino 如何将字符串转换为浮点或整数?
在Arduino项目中,我正在使用GPS,通过USB将坐标发送到Arduino。因此,传入坐标存储为字符串。有没有办法将GPS坐标转换为浮点或整数 我尝试了Arduino 如何将字符串转换为浮点或整数?,arduino,Arduino,在Arduino项目中,我正在使用GPS,通过USB将坐标发送到Arduino。因此,传入坐标存储为字符串。有没有办法将GPS坐标转换为浮点或整数 我尝试了int-gpslong=atoi(curlongitute)和float-gpslong=atof(curlongitute),但它们都会导致Arduino给出错误: error: cannot convert 'String' to 'const char*' for argument '1' to 'int atoi(const char
int-gpslong=atoi(curlongitute)
和float-gpslong=atof(curlongitute)
,但它们都会导致Arduino给出错误:
error: cannot convert 'String' to 'const char*' for argument '1' to 'int atoi(const char*)'
有人有什么建议吗?只需调用
字符串
对象(例如curlongitute.toInt()
),就可以从字符串
中获得int
如果需要浮点
,可以将atof
与以下方法结合使用:
sscanf(卷曲度、%i、&gpslong)
或sscanf(卷曲度、%f、&gpslong)
?当然,根据字符串的外观,您可能需要修改格式字符串。c\u str()
将为您提供字符串缓冲区常量char*指针。因此,您可以使用转换函数:
int-gpslong=atoi(curlongite.c_str())
float-gpslong=atof(curlongite.c_str())
在Arduino IDE中将字符串转换为长字符串:
//stringToLong.h
long stringToLong(String value) {
long outLong=0;
long inLong=1;
int c = 0;
int idx=value.length()-1;
for(int i=0;i<=idx;i++){
c=(int)value[idx-i];
outLong+=inLong*(c-48);
inLong*=10;
}
return outLong;
}
//stringToLong.h
long stringToLong(字符串值){
long-outLong=0;
长inLong=1;
int c=0;
int idx=value.length()-1;
对于(int i=0;toint是正确的)谢谢。在这种情况下,我如何使用ToCARARTHORE?我似乎无法理解。@ XJKH3VK:添加了一个例子。注意这些是ARDUINO <代码>字符串 S,而不是C++ <代码>字符串< /COD> S.@ CABI,谢谢。工作工作)这是一个纯英语的网站。而且,这个答案没有添加任何有用的内容,也没有解释它在做什么(而且非常复杂)。
//stringToLong.h
long stringToLong(String value) {
long outLong=0;
long inLong=1;
int c = 0;
int idx=value.length()-1;
for(int i=0;i<=idx;i++){
c=(int)value[idx-i];
outLong+=inLong*(c-48);
inLong*=10;
}
return outLong;
}
String stringOne, stringTwo, stringThree;
int a;
void setup() {
// initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
stringOne = 12; //String("You added ");
stringTwo = String("this string");
stringThree = String();
// send an intro:
Serial.println("\n\nAdding Strings together (concatenation):");
Serial.println();enter code here
}
void loop() {
// adding a constant integer to a String:
stringThree = stringOne + 123;
int gpslong =(stringThree.toInt());
a=gpslong+8;
//Serial.println(stringThree); // prints "You added 123"
Serial.println(a); // prints "You added 123"
}