【问题标题】:Create a new char to pass to method in C [closed]创建一个新字符以传递给 C 中的方法 [关闭]
【发布时间】:2020-11-15 19:43:28
【问题描述】:

我有以下来自 RadioHead 库的代码。本质上,我想将以下变量作为 1 个字符数组传递给一个方法。变量:From、data 和“newData:”

代码:

 if (manager.recvfromAckTimeout(buf, &len, 1000, &from))
    {
      Serial.print("got reply from : 0x");
      Serial.print(from, HEX);
      Serial.print(": ");
      Serial.println((char*)buf);
      
      client.send("newData:" + from + ";" +(char*)buf);
    }

错误在代码的最后一行。这是一种将数据发送到 websocket 的方法。我收到以下错误:

exit status 1
invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

我该如何解决这个问题?在 C 中使用字符串和字符是一件很恐怖的事情。当我出于某种原因使用字符串时,我的 Arduino 会冻结。我正在尝试仅使用字符来找到一种方法

基本上我想要的是这样的

char newData[] = "newData:" + from + (char*)buf;

【问题讨论】:

  • buf 的确切类型是什么?
  • 看起来像 uint8。这是我正在使用的库的源代码,它只是方法的第一部分。 - bool RHRouter::recvfromAck(uint8_t* buf, uint8_t* len, uint8_t* source, uint8_t* dest, uint8_t* id, uint8_t* flags, uint8_t* hops)
  • 您是否对 C++ 解决方案感兴趣,或者您只是使用该标签来获得更多关注?
  • 所以缓冲区是计数的,不一定是 NUL 终止的:C++ 怎么知道如何从中正确构造字符串?为什么不创建自己的本地 char 缓冲区,将消息格式化到其中,然后将该 NUL 终止的缓冲区传递给 client.send()
  • C 不能使用+ 运算符连接字符串。请改用strcat

标签: c++ c arduino


【解决方案1】:

您不能在 C 中将字符串文字和 char* 实例与 + 运算符一起“添加”以获得连贯的字符串。也不是在 C++ 中,除非 std::string 在混合中。

所以不要这样:

client.send("newData:" + from + ";" +(char*)buf);

这个:

std::ostringstream ss;
ss << "newData:";
ss << from;
ss << ";";
std::string msg = ss.str() + std::string((char*)buf,len);
client.send(msg.c_str());

我假设buf 是二进制数据,其中可能包含空字符,而不仅仅是 ascii 字符。因此,len 与字符串 s 的显式连接。

【讨论】:

  • 感谢您的帮助。不幸的是,尝试此解决方案时会出现此错误:'operator+' 不匹配(操作数类型为 'std::__cxx11::string {aka std::__cxx11::basic_string}' 和 'uint8_t {aka unsigned char}' )
  • from 是什么类型?
  • 看起来像它的 uint8_t
  • std::string s = std::string("newData") + (char*)from + ";";
  • from 是可打印的吗?或者它是代表地址的二进制事物?如果是前者,那还好。如果是后者,这将无法可靠地工作。我需要更多关于 from 的含义的详细信息(以及您为什么尝试将其添加到字符串中)
猜你喜欢
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
相关资源
最近更新 更多