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

后端 未结 13 2176
半阙折子戏
半阙折子戏 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:15

    int main()
    {
      char d = 'd';
      std::string y("Hello worl");
    
      y += d;
      y.push_back(d);
      y.append(1, d); //appending the character 1 time
      y.insert(y.end(), 1, d); //appending the character 1 time
      y.resize(y.size()+1, d); //appending the character 1 time
      y += std::string(1, d); //appending the character 1 time
    }
    

    Note that in all of these examples you could have used a character literal directly: y += 'd';.

    Your second example almost would have worked, for unrelated reasons. char d[1] = { 'd'}; didn't work, but char d[2] = { 'd'}; (note the array is size two) would have been worked roughly the same as const char* d = "d";, and a string literal can be appended: y.append(d);.

提交回复
热议问题