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

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

    There are more options possible to use to concatenate integer (or other numerric object) with string. It is Boost.Format

    #include 
    #include 
    int main()
    {
        using boost::format;
    
        int age = 22;
        std::string str_age = str(format("age is %1%") % age);
    }
    

    and Karma from Boost.Spirit (v2)

    #include 
    #include 
    #include 
    int main()
    {
        using namespace boost::spirit;
    
        int age = 22;
        std::string str_age("age is ");
        std::back_insert_iterator sink(str_age);
        karma::generate(sink, int_, age);
    
        return 0;
    }
    

    Boost.Spirit Karma claims to be one of the fastest option for integer to string conversion.

提交回复
热议问题