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

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

    It seems to me that the simplest answer is to use the sprintf function:

    sprintf(outString,"%s%d",name,age);
    
    0 讨论(0)
  • 2020-11-22 03:24
    #include <string>
    #include <sstream>
    using namespace std;
    string concatenate(std::string const& name, int i)
    {
        stringstream s;
        s << name << i;
        return s.str();
    }
    
    0 讨论(0)
  • 2020-11-22 03:26

    If you are using MFC, you can use a CString

    CString nameAge = "";
    nameAge.Format("%s%d", "John", 21);
    

    Managed C++ also has a string formatter.

    0 讨论(0)
  • 2020-11-22 03:28

    This is the easiest way:

    string s = name + std::to_string(age);
    
    0 讨论(0)
  • 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 <iostream>
    #include <locale>
    #include <string>
    
    template <class Facet>
    struct erasable_facet : Facet
    {
        erasable_facet() : Facet(1) { }
        ~erasable_facet() { }
    };
    
    void append_int(std::string& s, int n)
    {
        erasable_facet<std::num_put<char,
                                    std::back_insert_iterator<std::string>>> facet;
        std::ios str(nullptr);
    
        facet.put(std::back_inserter(s), str,
                                         str.fill(), static_cast<unsigned long>(n));
    }
    
    int main()
    {
        std::string str = "ID: ";
        int id = 123;
    
        append_int(str, id);
    
        std::cout << str; // ID: 123
    }
    
    0 讨论(0)
  • 2020-11-22 03:29

    In C++20 you'll be able to do:

    auto result = std::format("{}{}", name, age);
    

    In the meantime you can use the {fmt} library, std::format is based on:

    auto result = fmt::format("{}{}", name, age);
    

    Disclaimer: I'm the author of the {fmt} library and C++20 std::format.

    0 讨论(0)
提交回复
热议问题