0

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)

  • [Dupe that explains the problem](https://stackoverflow.com/questions/5705956/c-adding-string-literal-to-char-literal) and [Dupe that gives the solution](https://stackoverflow.com/questions/44369760/add-a-character-between-strings-in-c) – Jason Aug 18 '22 at 10:12
  • *"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`."* -- more precisely: you have a `std::string` with the name `word` and you want to add the first letter of it to a **string literal** and store them to `std::string` `word1`. – JaMiT Aug 18 '22 at 10:27

1 Answers1

3

"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];
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185