【问题标题】:appending variables in a string separated by commas在以逗号分隔的字符串中附加变量
【发布时间】:2015-06-24 10:32:20
【问题描述】:

我在 arduino 中有 3 个变量声明为字符数组:id、temp、湿度。

我如何附加它们并将它们写为用逗号分隔的字符串。

例如:id:12,temp:23,湿度:50

到目前为止,这是我的代码。

亲切的问候

char id[2];
char humidity;
char temp[2];
string example;

void setup()
{
//setup stuff
 }

void loop(void)
{
// Receive message

e = sx1272.receivePacketTimeout(10000);
e = sx1272.getRSSIpacket();

Serial.println(e, DEC);

if( sx1272.packet_received.length < 14 )
{
Serial.println("Missing data");
}
else
{

id[0] = sx1272.packet_received.data[0]; 
id[1] = sx1272.packet_received.data[1];  
humidity = sx1272.packet_received.data[4]; 
temp[0] = sx1272.packet_received.data[9]; 
temp[1] = sx1272.packet_received.data[10]; 
}

example = String.format("id:%c,crc:%c,humidity:%c)", id, crc, humidity);

【问题讨论】:

    标签: string arduino append


    【解决方案1】:

    您也可以使用字符串格式以更精确。

     String example = String.format("id:%s,temp:%s,humidity:%s", id, temp, humidity)
    

    【讨论】:

    • 嗨@toshkinl,变量是char数组有关系吗?它们不是字符串 - 我可以在它们上使用 .format 吗?我收到错误 expected primary-expression before '.' token 谢谢
    • 在哪里声明字符串并不重要,当你有你的字段值时,你可以声明它。而且char数组和字符串几乎是一样的。字符串是不可变的。字符数组不是。 string 是用下面的 char 数组实现的,但是每次您尝试修改它(例如使用连接、替换等)时,它都会为您提供一个新的 String 对象。我认为arduino是用java编写的。幸运的是它是 C++。您可以查看此link 以查看 c++ 字符串格式替代方案。
    • 感谢您的解释。你知道为什么它会给出expected primary-expression before '.' token 错误吗?我已经修改了原始帖子中的代码。亲切的问候
    • 因为我已经给了你字符串格式的java代码。你需要c++一个from here
    猜你喜欢
    • 2012-08-12
    • 2021-10-10
    • 2013-06-11
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    相关资源
    最近更新 更多