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

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

    Here is an implementation of how to append an int to a string using the parsing and formatting facets from the IOStreams library.

    #include 
    #include 
    #include 
    
    template 
    struct erasable_facet : Facet
    {
        erasable_facet() : Facet(1) { }
        ~erasable_facet() { }
    };
    
    void append_int(std::string& s, int n)
    {
        erasable_facet>> facet;
        std::ios str(nullptr);
    
        facet.put(std::back_inserter(s), str,
                                         str.fill(), static_cast(n));
    }
    
    int main()
    {
        std::string str = "ID: ";
        int id = 123;
    
        append_int(str, id);
    
        std::cout << str; // ID: 123
    }
    

提交回复
热议问题