0

Well I am trying to save phone number as a string. For ease of use I want to add "+" character programmatically. Like this:

String cepNo ="+" + "901234567";

But program gives this error.

exit status 1
invalid operands of types 'const char [2]' and 'const char [13]' to binary 'operator+'

How to add "+" beginning of the string.

  • 1
    A string literal isn't a String. You can't concatenate them like that. This is C, not BASIC. – Majenko Jul 25 at 11:29
  • The arduino error is on the +, not the "+". – Tirdad Sadri Nejad Jul 25 at 11:56
3

You cannot add C strings (i.e. NUL-terminated arrays of char) with the + operator. It only works with String objects. You can, though, add a String object and a C-string, because in this case the compiler implicitly converts the C string into a String object:

String phone_number = "901234567";
phone_number = "+" + phone_number;

The last line is interpreted by the compiler as

phone_number = String("+") + phone_number;

That being said, I encourage you to try to avoid String objects if possible. These use dynamic memory allocation which carries the risk of heap fragmentation. The same thing can be achieved with plain C strings:

char phone_number[] = "901234567";
char full_phone_number[strlen(phone_number) + 2];
strcpy(full_phone_number, "+");
strcat(full_phone_number, phone_number);

Note the size of the second string: strlen(phone_number) + 2. You need one extra char for the + sign, and another one for the NUL string terminator.

Now, with C strings you can do better, and avoid copying: reserve enough room in an array for the full number (“+” included), and then fill the digits starting from the second slot in the char array. You can then add the + sign later:

char phone_number[16];
strcpy(phone_number + 1, "901234567");
phone_number[0] = '+';

Although I personally would write the “+” sign and a NUL while initializing the array:

char phone_number[16] = "+";
strcat(phone_number, "901234567");
| improve this answer | |
1

use String cepNo = String("+") + "901234567"; or String a = "+"; String cepNo = a + "901234567";

| improve this answer | |
  • Or, simply don't use the + operator. – DataFiddler Jul 26 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.