如何将String转换为float或int?

时间:2013-08-13 03:07:20

标签: arduino

在Arduino程序中我正在研究GPS通过USB将坐标发送到arduino。因此,传入的坐标存储为字符串。有没有办法将GPS坐标转换为float或int?

我已尝试int gpslong = atoi(curLongitude)float gpslong = atof(curLongitude),但它们都会导致Arduino发出错误:

error: cannot convert 'String' to 'const char*' for argument '1' to 'int atoi(const char*)'

有人有任何建议吗?

5 个答案:

答案 0 :(得分:23)

只需致电int对象上的toInt(例如String),您就可以从String获得curLongitude.toInt()

如果您想要float,可以将atoftoCharArray方法结合使用:

char floatbuf[32]; // make this at least big enough for the whole string
curLongitude.toCharArray(floatbuf, sizeof(floatbuf));
float f = atof(floatbuf);

答案 1 :(得分:2)

c_str() 将为您提供字符串缓冲区const char *指针。

所以你可以使用你的转换功能:
int gpslong = atoi(curLongitude.c_str()) {
{1}}

答案 2 :(得分:0)

sscanf(curLongitude, "%i", &gpslong)sscanf(curLongitude, "%f", &gpslong)怎么样?根据字符串的外观,您可能必须修改格式字符串。

答案 3 :(得分:0)

在Arduino IDE中将String转换为Long:

    //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;
    }

答案 4 :(得分:-2)

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"
}