The goal is to get the first, middle, and last name initials each followed by a period.
string first;
string middle;
string last;
string result;
The expression is typed in the string result.
I typed:
result = first[0] + "." + middle[0] + "." last[0] + ".";
And received an the following error:
invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’
But when I remove the "." for the above statement, it compiles without any error.
The solution ended up being:
result = first.substr(0,1) + "." + middle.substr(0,1) + "." last.substr(0,1) + ".";
So my question is that, why do I get a compile error when I add .
with string[0]
, but not when I add .
with string.substr(0,1)
?
first[0] + "."
In this expression:
first
is a std::string
.first[0]
is a char
(some immaterial technical details omitted)."."
is a char [2]
(an array of two char
values).In C++, it is illegal to add a char
value to a char [2]
, you can't just add char
to an array. That's simply not allowed in C++. There are various rules about what you can do to what else in C++. You can add numerical values to other numerical values. You can add an integer value to a pointer. Finally, a class can define its own +
operator. That's pretty much it. None of this applies to this expression, hence the compilation error.
Now, if you go back and reread the actual error message that your compiler showed you, it should make perfect sense.