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

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

    #include 
    
    template 
    inline std::string to_string (const T& t)
    {
       std::stringstream ss;
       ss << t;
       return ss.str();
    }
    

    Then your usage would look something like this

       std::string szName = "John";
       int numAge = 23;
       szName += to_string(numAge);
       cout << szName << endl;
    

    Googled [and tested :p ]

提交回复
热议问题