How to concatenate a std::string and an int?

前端 未结 23 2643
南方客
南方客 2020-11-22 02:40

I thought this would be really simple but it\'s presenting some difficulties. If I have

std::string name = \"John\";
int age = 21;

How do I

23条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 03:33

    If you'd like to use + for concatenation of anything which has an output operator, you can provide a template version of operator+:

    template  std::string operator+(L left, R right) {
      std::ostringstream os;
      os << left << right;
      return os.str();
    }
    

    Then you can write your concatenations in a straightforward way:

    std::string foo("the answer is ");
    int i = 42;
    std::string bar(foo + i);    
    std::cout << bar << std::endl;
    

    Output:

    the answer is 42
    

    This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.

提交回复
热议问题