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

前端 未结 23 2344
南方客
南方客 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:36

    The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:

    #include 
    #define MAKE_STRING(tokens) /****************/ \
        static_cast(          \
            std::ostringstream().flush() << tokens \
        ).str()                                    \
        /**/
    

    Now you can format strings like this:

    int main() {
        int i = 123;
        std::string message = MAKE_STRING("i = " << i);
        std::cout << message << std::endl; // prints: "i = 123"
    }
    

提交回复
热议问题