如何修复“没有合适的转换函数从”String“到”const char *“存在”?

时间:2016-02-05 00:08:57

标签: c++ string syntax char

我不确定如何实现这一目标,我已经搜索并尝试了很多不同的东西,但我不能让它发挥作用? strcpy(host,DATA);是什么给了我错误。

char host[60] = "www.yahoo.com";

void loop() {
    String content = "";
    char character;
    while (Serial.available()) {
        character = Serial.read();
        content.concat(character);
    }
    if (content != "") {
        String CMD = getValue(content, '|', 0);
        String DATA = getValue(content, '|', 1);

        if (CMD == "SSID")
        {
            Serial.println("Your CMD is:" + CMD + " And your DATA is:" + DATA);
        }
        else if (CMD == "PASS")
        {
            Serial.println("Your CMD is:" + CMD + " And your DATA is:" + DATA);
        }
        else if (CMD == "HOST")
        {
            Serial.println("Your CMD is:" + CMD + " And your DATA is:" + DATA);

            strcpy(host, DATA);
        }
    }
    delay(100);
}

1 个答案:

答案 0 :(得分:3)

如果Stringstd::string,则可以

strcpy(host, DATA.c_str());

如果它是自定义类,例如

class String
{
char buffer[20];

//add a method c_str() for example like the std::string does

const char * c_str() { return buffer; }

//or just go yolo and overload the operator const char * like a boss

operator const char *() { return buffer;  }

};

现在你所要做的就是strcpy(buff, DATA),并且会使用operator const char * ()