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

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

    This problem can be done in many ways. I will show it in two ways:

    1. Convert the number to string using to_string(i).

    2. Using string streams.

      Code:

      #include 
      #include 
      #include 
      #include 
      using namespace std;
      
      int main() {
          string name = "John";
          int age = 21;
      
          string answer1 = "";
          // Method 1). string s1 = to_string(age).
      
          string s1=to_string(age); // Know the integer get converted into string
          // where as we know that concatenation can easily be done using '+' in C++
      
          answer1 = name + s1;
      
          cout << answer1 << endl;
      
          // Method 2). Using string streams
      
          ostringstream s2;
      
          s2 << age;
      
          string s3 = s2.str(); // The str() function will convert a number into a string
      
          string answer2 = "";  // For concatenation of strings.
      
          answer2 = name + s3;
      
          cout << answer2 << endl;
      
          return 0;
      }
      

提交回复
热议问题