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

后端 未结 13 2099
半阙折子戏
半阙折子戏 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);.

    0 讨论(0)
  • 2020-11-29 16:17
    str.append(10u,'d'); //appends character d 10 times
    

    Notice I have written 10u and not 10 for the number of times I'd like to append the character; replace 10 with whatever number.

    0 讨论(0)
  • 2020-11-29 16:17

    Also adding insert option, as not mentioned yet.

    std::string str("Hello World");
    char ch;
    
    str.push_back(ch);  //ch is the character to be added
    OR
    str.append(sizeof(ch),ch);
    OR
    str.insert(str.length(),sizeof(ch),ch) //not mentioned above
    
    0 讨论(0)
  • 2020-11-29 16:20

    the problem with:

    std::string y("Hello worl");
    y.push_back('d')
    std::cout << y;
    

    is that you have to have the 'd' as opposed to using a name of a char, like char d = 'd'; Or am I wrong?

    0 讨论(0)
  • 2020-11-29 16:21

    I found a simple way... I needed to tack a char on to a string that was being built on the fly. I needed a char list; because I was giving the user a choice and using that choice in a switch() statement.

    I simply added another std::string Slist; and set the new string equal to the character, "list" - a, b, c or whatever the end user chooses like this:

    char list;
    std::string cmd, state[], Slist;
    Slist = list; //set this string to the chosen char;
    cmd = Slist + state[x] + "whatever";
    system(cmd.c_str());
    

    Complexity may be cool but simplicity is cooler. IMHO

    0 讨论(0)
  • 2020-11-29 16:22

    Use push_back():

    std::string y("Hello worl");
    y.push_back('d')
    std::cout << y;
    
    0 讨论(0)
提交回复
热议问题