c++stringcharesp8266sming

Convert char* into String


I am using ESP8266 Wifi chip with the SMING framework which uses C++. I have a tcpServer function which receives data from a TCP port. I would like to convert the incoming char *data into String data type. This is what I did.

bool tcpServerClientReceive(TcpClient& client, char *data, int size)
{
    String rx_data;
    rx_data = String(data);
    Serial.printf("rx_data=%s\r",rx_data);
}

The contents of rx_data is rubbish. What is wrong with the code? How to make rx_data into a proper string?


Solution

  • Why what you are doing is wrong:

    A C style string is an array of char where the last element is a 0 Byte. This is how functions now where the string ends. They scan the next character until they find this zero byte. A C++ string is a class which can hold additional data.

    For instance to get the length of a string one might choose to store the length of the stirng in a member of the class and update it everytime the string is modified. While this means additional work if the string is modified it makes the call t length trivial and fast, since it simply returns the stored value.

    For C Strings on the other hand length has to loop over the array and count the number of characters until it finds the null byte. thus the runime of strlen depends on the lengh of the string.

    The solution:

    As pointed out above you have to print it correctly, try either:

    #include <iostream>
    ...
    std::cout << "rx_data=" << rx_data << std::endl;
    

    or if you insist on printf (why use c++ then?) you can use either string::c_str(), or (since C++11, before the reutrned array might not be null terminated) string::data(): your code would become:

    Serial.printf("rx_data=%s\r",rx_data.c_str());
    

    I would suggest you have a look at std::string to get an idea of the details. In fact if you have the time a good book could help explaining a lot of important concepts, including containers, like std::string or std::vector. Don't assume that because you know C you know how to write C++.