How to add int to string in C++

In this article, we are going to learn, how to add int to string in c++. We will also learn to append or concatenate an Integer to a string in C++. We will learn this by using multiple techniques.

  • Using += Operator and std::to_string Function to Append Int to String
  • Using append() Method to Add Int to String

1. Using += Operator and std::to_string Function to Append Int to String


In this example, we are going to use the += operator and to_string() function to append an integer to a string. += operator is overloaded for the string class to add two strings. so we are using the to_string() function to convert the number to string and then add it to another string.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    string str = "One Two Three Four";
	
    int num = 1234;

    str += to_string(num);
    cout <<"The Concatinated String is :" <<str << endl;

    return 0;
}

Output

The Concatinated String is :One Two Three Four1234

2.How to add Decimal to string in C++


Similarly, we are doing the same for the numbers with decimal points. to_string() function will convert the floating-point number to a string and then just simply add to another string.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    string str = "One Two Three Four";
    float fnum = 12.34;

    str += to_string(fnum);
    cout <<"The Concatinated String is :" <<str << endl;

    return 0;
}

Output

The Concatinated String is :One Two Three Four12.340000

3. Using the append() Method to Add Int to String


Another method that we can use to add an integer number to a string is by using the append() function of the String class. This function also accepts a string as an argument to append it to another string. Here we are making use of the to_string() function to convert the number to a string and then passing it to the append function.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "One Two Three Four";
    int num = 1234;

    str.append(to_string(num));
    cout <<"The Concatinated String is :" <<str << endl;

    return 0;
}

Output

The Concatinated String is :One Two Three Four1234

Summary

In this post,we have learned how to add int to string in C++