2 minute read

Introduction

In this tutorial, you will learn how to convert an int (such as 3) to a string format in the C++ programming language.

For instance, given an int (integer type) such as 14. Then, we would like to get a string like “14”

Method #1: Using std::to_string()

We can use the to_string() function to convert an integer to a string. It is a function from the std library, so we will need to import the following libraries into the header area of our code.

#include <string> //Add this
#include <iostream> //Add this

int main()
{
    int x = 412;
	std::string myString = std::to_string(x);
	std::cout << "myString is: " << myString << std::endl; //Returns "myString is: 412"
	return 0;
}

NOTE: Do not forget to include the string library, otherwise we may get the std::to_string is not a member of std error.

Output:

myString is: 412

Method #2: Using std::stringstream

Another way to convert an int to a string in C++ is by using the std::stringstream class from the <sstream> library. This class allows you to read and write to a string as if it were a stream, such as a file or a network connection. Here’s an example of how to use it to convert an int to a string:

#include <sstream> //Add this
#include <iostream> //Add this

int main()
{
    int x = 412;
	std::stringstream ss;
	ss << x;
	std::string myString = ss.str();
	std::cout << "myString is: " << myString << std::endl; //Returns "myString is: 412"
	return 0;
}

Output:

myString is: 412

Method #3: Using std::sprintf

We can also use the std::sprintf function to convert an int to a string. It is a standard C function for creating formatted output. Here’s an example of how to use it to convert an int to a string in C++:

#include <cstdio> //Add this
#include <iostream> //Add this

int main()
{
    int x = 412;
    char buffer[256];
    std::sprintf(buffer, "%d", x);
    std::string myString(buffer);
    std::cout << "myString is: " << myString << std::endl; //Returns "myString is: 412"
    return 0;
}

Output:

myString is: 412

References

Read more about the std::to_string function here: https://en.cppreference.com/w/cpp/string/basic_string/to_string

Read more about the std::stringstream function here: https://cplusplus.com/reference/sstream/stringstream/

Read more about the sprintf function here: https://cplusplus.com/reference/cstdio/sprintf/