Consider the following code:
#include <iostream>
#include <typeinfo>
int main(){
std::string word = "This is string";
std::string word1 = "a" + word[0];
std::cout << word1;
}
As you can see, i heve a string with the name word
and i want to add first letter of it to another string and store them to string word1
. when i run code, I expect that output is aT
, but the output is ╨≥ ╨≥ ╨≥ ╨≥ P≥ ►≥ @≥ ╕♠≥
! What does this mean? How do i fix it? (Also note that my IDE is Code::Blocks 20.03)
"a"
is not a string (well, its a c-string, but not a std::string
, and a c-string is just an array). Its a const char[2]
and decays to a pointer when +
is applied. There is an operator+
for std::string
though:
std::string word1 = std::string("a") + word[0];
or
std::string word1 = "a"s + word[0];