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.
-
1A string literal isn't a String. You can't concatenate them like that. This is C, not BASIC.Majenko– Majenko2020年07月25日 11:29:02 +00:00Commented Jul 25, 2020 at 11:29
-
The arduino error is on the +, not the "+".Tirdad the Whitehand– Tirdad the Whitehand2020年07月25日 11:56:40 +00:00Commented Jul 25, 2020 at 11:56
2 Answers 2
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");
use String cepNo = String("+") + "901234567";
or
String a = "+"; String cepNo = a + "901234567";
-
Or, simply don't use the + operator.DataFiddler– DataFiddler2020年07月26日 17:23:35 +00:00Commented Jul 26, 2020 at 17:23