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

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

问题描述

在Arduino程序中,我正在GPS上通过USB将坐标发送到arduino.因此,传入的坐标存储为字符串.有什么方法可以将GPS坐标转换为float或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?

我尝试了 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*)'

有人有什么建议吗?

推荐答案

您只需调用

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

如果要使用 float ,则可以将 atof toCharArray 方法:

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天全站免登陆