c++stringcharconcatenation

How do I append a char to a std::string?


I'm writing a programming language in C++ and I need to append a char to an std::string.

I've read some other posts on Stack Oferflow about this issue, but none of them solved mine. The first thing I tried was something like this:

#include <iostream>
#include<string>

int main() {
    std::string str;
    char ch;

    str = "Hello";
    ch = '!';

    str = str + ch;
}

but G++ said that I can't concatenate a string with a character because of the different types. G++ error:

no operator "+" matches these operands

On Stack Overflow I read that I can use the .append() method, but the compiler didn't even recognize this method saying

no instance of overloaded function "std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::append [with _CharT=char, _Traits=std::char_traits<char>, _Alloc=std::allocator<char>]" matches the argument list

Can someone help me?


Solution

  • you have many methods. Some here:

    #include <iostream>
    #include <string>
    
    int main()
    {
        std::string str = "Hello";
        str.push_back('!');
        std::cout << str << std::endl; 
    
        str += '@';
        std::cout << str << std::endl; 
    
        str = str + '*';
        std::cout << str << std::endl; 
    
        str.append(1, '#'); 
        std::cout << str << std::endl; 
    
        str.insert(str.size(), 1, 'o'); 
        std::cout << str << std::endl; 
    }
    

    https://godbolt.org/z/szMdz1hYq