以字符串形式连接const char *

时间:2019-01-20 11:44:02

标签: c++ arduino arduino-ide

我正在尝试将const char*变量与连接在一起放在字符串中,这些只是初始化变量。这是我在String input中尝试执行的操作:

const char* topic1 = "home/bathroomlight";
const char* topic2 = "home/bathroomfan";
const char* topic3 = "home/dressingroomlight";
const char* topic4 = "home/makeuplight";

const char* topic1_status = "home/bathroomlight/status";
const char* topic2_status = "home/bathroomfan/status";
const char* topic3_status = "home/dressingroomlight/status";
const char* topic4_status = "home/makeuplight/status";

String input = "{ \"Bath Room Light\" : { \"pin\" : 1, \"status\" : \"off\", \"type\" : \"light\", \"command_topic\" : "+  topic1 +", \"state_topic\" : "+topic1_status +" }, \"Bathroom Fan\" : { \"pin\" : 2, \"status\" : \"off\", \"type\" : \"fan\", \"command_topic\" : "+topic2+", \"state_topic\" : "+topic2_status+" }, \"Dressing Room Light\" : { \"pin\" : 4, \"status\" : \"off\", \"type\" : \"light\", , \"command_topic\" : "+ topic3 +", \"state_topic\" : "+ topic3_status +" }, \"Makeup Light\" : { \"pin\" : 3, \"status\" : \"off\", \"type\" : \"light\", \"command_topic\" : "+ topic4 +", \"state_topic\" : "+ topic4_status +" } }";

当我尝试将这些值附加到input字符串时。它不允许我。我猜上面的值在const char*中,我该如何添加呢?任何建议都会有所帮助。

2 个答案:

答案 0 :(得分:2)

问题在于,本地字符串(以空字符终止的字符数组)和通过字符指针引用的字符串不会使用{{ 1}}运算符。但是+库的字符串类Arduino可以。

因此,首先必须构造一个String类对象,然后将其字符数组连接

String

答案 1 :(得分:1)

不允许,因为您无法连接const char *

为此,您需要制作一个std::string对象,然后您可以向该对象添加const char *(因为std::string的{​​{1}}包含一个{ {1}}):

operator+