如何将 String 转换为 float 或 int? [英] How do you convert a String to a float or int?

查看:38
本文介绍了如何将 String 转换为 float 或 int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在处理的 Arduino 程序中,GPS 通过 USB 将坐标发送到 arduino.因此,传入的坐标存储为字符串.有没有办法将 GPS 坐标转换为浮点数或整数?

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?

我试过 int gpslong = atoi(curLongitude)float gpslong = atof(curLongitude),但它们都导致 Arduino 出错:

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*)'

大家有什么建议吗?

推荐答案

你可以通过调用 toIntString 对象上(例如 curLongitude.toInt()).

You can get an int from a String by just calling toInt on the String object (e.g. curLongitude.toInt()).

如果你想要一个 float,你可以将 atoftoCharArray 方法:

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

这篇关于如何将 String 转换为 float 或 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆