如何将获取的字符串数据转换为字符数组?

问题描述 投票:0回答:1

我正在做这个基于IoT的项目,在nodeMCU的帮助下向连接的显示器显示数据(我在这种情况下使用了MAX7219模块)。这里的想法是存储在我的firebase数据库中的字符串将显示在LED显示屏上。

我从数据库获取值到我的nodeMCU没有遇到任何麻烦,但是因为我正在使用的代码(Max72xx_Message_serial,可以作为max72xx库的一个例子),将该字符串转换为char数组存在这个小问题。使用char数组,但我只能以字符串格式获取存储的数据。我已修改该代码以便与firebase连接,但主要问题是将从数据库中提取的字符串转换为char数组。

我试过toCharArray()但它仍然显示转换错误。

void readfromfirebase(void)
{
  static uint8_t  putIndex = 0;
  int n=1;
  while (Firebase.available())
   {
    newMessage[putIndex] = (char)Firebase.getString("Submit Message"); // this line produces the error
    if ((newMessage[putIndex] == '\n') || (putIndex >= BUF_SIZE-3)) // end of message character or full buffer
    {
      // put in a message separator and end the string
      newMessage[putIndex++] = ' ';
      newMessage[putIndex] = '\0';
      // restart the index for next filling spree and flag we have a message waiting
      putIndex = 0;
      newMessageAvailable = true;
    }
    else if (newMessage[putIndex] != '\r')
      // Just save the next char in next location
      {putIndex++;}
      n++;
  }
}
c++ firebase arduino arduino-ide nodemcu
1个回答
1
投票

我认为你混淆了这些类型

getString返回一个String对象,它可以使用String类的方法转换为char []。

我假设你的newMessage是char []或char *类型。然后我建议你去String.c_str()方法,因为它返回一个C样式的以null结尾的字符串,意思是char *。请参阅https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/c_str/以供参考。

它还将字符串的最后一个字符设置为0.因此strlen,strcmp等方法可以正常工作。

!小心不要修改c_str()返回的数组,如果你想修改它,你可以复制char []或使用string.toCharArray(buf, len)

您的代码可能如下所示。

    String msg = Firebase.getString("Submit Message");
    newMessage = msg.c_str();
   // rest of your code

如果newMessage是一个存储多个消息的缓冲区,意思是char* newMessage[3]

    String msg = Firebase.getString("Submit Message");
    newMessage[putIndex] = msg.c_str();
   // rest of your code

要小心,因为您在数组中存储多个字符,所以使用strcmp来比较这些数组!

如果你是C的新手我会推荐阅读。

© www.soinside.com 2019 - 2024. All rights reserved.