Question

I am writing an Arduino library for simple data transfers between the Arduino and a computer using a serial feed. I have created the library, etc. However, I am having issues with taking a char array, and adding a colon (':') to it. That is,

//Sends data via println()
void simpleTransfer::sendData(char *name, char *data){
    char *str = name + ": " + data + ",";
    _serial->println(str); //Sends in form 'name: data,'
}

This should take the name of a variable that I want to send, add a colon and a space, and the data I want to send and finally a comma. However, I instead get error messages:

invalid operands of types 'char*' and 'const char [3]' to binary 'operator+'

What is the reason?

Était-ce utile?

La solution 2

You could use sprintf:

char str[64];  // Or whatever length you need to fit the resulting string
sprintf(str, "%s:%s,", name, data);

Or strcpy/strcat:

char str[64];
strcpy(str, name);
strcat(str, ":");
strcat(str, data);
strcat(str, ",");


Or just use C++'s std::string.

Autres conseils

Short answer: use std::string to create the concatenated string.

 std::string s = ((std::string(name) + ": ") + data) + ",";
_serial->println( s.c_str() );

Long answer: when concatenating C-style strings, you need a destination buffer that's large enough to hold the result. If you know the maximum size that the result can ever get to, you can declare a local array of that size, and use sprintf as the other answers explains.

Or, if you don't know the size in advance, you can use a combination of strlen and new[] to allocate a dynamically size buffer, do the printing, then delete[] the buffer. But don't do this! Use a string class instead, either std::string, or as Drew Dormann mentions in the comments below, an Arduino specific String class.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top