Search code examples
c++stringconstructorcharinitialization

Why cant we assign char to strings?


in C++, I noticed if I make a string str="kls";, then I can't write string s1=str[0]; I have to instead write:

string s1;
s1=str[0];

Why so?


Solution

  • The reason is that the class std::string does not have a constructor that accepts a single argument of the type char. While there is a copy assignment operator that accepts as an argument a single character.

    basic_string& operator=(charT c);
    

    You could write

    std::string s1( 1, str[0] );
    

    or (there is used the initializating-list constructor)

    std::string s1 = { str[0] };
    

    or

    std::string s1 = { str, 0, 1 };