C++ create string of text and variables

前端 未结 6 943

I\'m trying to do something very simple and yet, after an hour of so of searching a I can\'t find a suitable answer so I must be missing something fairly obvious.

I\

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 11:16

    std::string var = "sometext" + somevar + "sometext" + somevar;
    

    This doesn't work because the additions are performed left-to-right and "sometext" (the first one) is just a const char *. It has no operator+ to call. The simplest fix is this:

    std::string var = std::string("sometext") + somevar + "sometext" + somevar;
    

    Now, the first parameter in the left-to-right list of + operations is a std::string, which has an operator+(const char *). That operator produces a string, which makes the rest of the chain work.

    You can also make all the operations be on var, which is a std::string and so has all the necessary operators:

    var = "sometext";
    var += somevar;
    var += "sometext";
    var += somevar;
    

提交回复
热议问题