0

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jacobsax
  • 37
  • 1
  • 7

2 Answers2

3

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.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • 1
    ... From what I can tell, Arduino's C++ implementation doesn't have header ``, but does provide a type `String` that would support the syntax you've written. Correct me if I'm wrong, anyone. :) – Drew Dormann Apr 10 '13 at 16:54
  • @DrewDormann: Oh, I wasn't aware Arduino had that! http://arduino.cc/en/Reference/StringObject – Mooing Duck Apr 10 '13 at 17:01
  • You really don't want to use standard C++ libraries on an Arduino: it's a low resource platform. For this reason it has its own string implementation. – angelatlarge Apr 11 '13 at 02:31
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.

Michael
  • 57,169
  • 9
  • 80
  • 125
  • Same comment as above: `std::string` is not appropriate for Arduino. the `sprintf` method is better, but requires pulling in certain libraries which significantly increase code size, also not desirable on Arduino – angelatlarge Apr 11 '13 at 02:32