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

后端 未结 13 2147
半阙折子戏
半阙折子戏 2020-11-29 15:58

The following fails with the error prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’

int main()
{
  char d = \'d\';
  std::s         


        
13条回答
  •  渐次进展
    2020-11-29 16:10

    To add a char to a std::string var using the append method, you need to use this overload:

    std::string::append(size_type _Count, char _Ch)
    

    Edit : Your're right I misunderstood the size_type parameter, displayed in the context help. This is the number of chars to add. So the correct call is

    s.append(1, d);
    

    not

    s.append(sizeof(char), d);
    

    Or the simpliest way :

    s += d;
    

提交回复
热议问题