How do you convert a String to a float or int?

一笑奈何 提交于 2020-12-02 06:05:14

问题


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?


回答1:


You can get an int from a String by just calling toInt on the String object (e.g. 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);



回答2:


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())




回答3:


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.




回答4:


Convert String to Long in 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;
    }



回答5:


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


来源:https://stackoverflow.com/questions/18200035/how-do-you-convert-a-string-to-a-float-or-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!