How To Convert Integer To String In C++

C++ is a popular programming language widely used for its flexibility in handling complex computing tasks. It is highly versatile and allows developers to perform various operations on different types of data, including integers and strings.

One common operation in C++ is the conversion of integer values to string format. This task is crucial in many programming scenarios, including data processing, file handling, and network communication, among others.

In this blog, we will explore different techniques for converting integers to string in C++, with practical examples to help you understand and implement these techniques in your coding projects.

So, whether you’re a beginner or an experienced developer looking to enhance your C++ programming skills.

Why is converting Integer to string in c++ is needed?

Converting an integer to a string in C++ is an operation that has multifarious applications.There are the some reasons why converting an integer to a string in C++ is needed:

  • Displaying integers as text: Displaying integers as text is one such justification that demands such a conversion. For instance, if one is constructing a user interface, there may arise circumstances where it becomes incumbent upon the developer to exhibit an integer as text on the screen, thereby necessitating the conversion of the integer to a string.
  • Concatenating integers with strings: Concatenating integers with strings is yet another rationale for such a conversion. Given the urgency to build strings that incorporate numbers, it may become necessary to concatenate integers with other strings. In such cases, the programmer is mandated to convert the integer to a string before proceeding with the concatenation process.
  • Input/output operations: Input/output operations are a crucial domain where converting integers to strings is a critical task. In the context of reading or writing data to a file or a network socket, the need to convert integers to strings is a sine qua non to send or receive them as text.

In conclusion, the process of transforming integer to string in c++ is an exceedingly commonplace operation that can be beneficially utilized in a broad spectrum of scenarios, particularly when dealing with textual data.

How To Convert Integer To String In C++

Here are six different approaches to how to convert integer to string in C++ with detailed solution steps, code, and output for each approach:

  1. Using stringstream
  2. Using to_string() function
  3. Using sprintf() function
  4. Using string stream operator
  5. Using recursion
  6. Using bitset

Let’s dive in more with examples to each approach.

Approach 1: Using stringstream

Description: This approach uses stringstream to convert an integer to a string. It involves creating a stringstream object, inserting the integer value into it, and then extracting the resulting string.

Pros:

  • Easy to use
  • Supports different types of data

Cons:

  • May be slower than other approaches

Code:

#include <sstream>
#include <string>
#include <iostream>

int main()
{
    // initialize integer value
    int num = 123;

    // create stringstream object
    std::stringstream ss;

    // insert integer value into stringstream object
    ss << num;

    // extract resulting string
    std::string str = ss.str();

    // output string
    std::cout << str << std::endl;

    return 0;
}

Output:

123

Code Explanation:

  1. We first declare an integer variable num with the value of 123.
  2. Then, we create a stringstream object ss.
  3. We insert the value of num into ss using the << operator.
  4. We extract the resulting string using the str() function of ss.
  5. Finally, we output the resulting string using std::cout.

Approach 2: Using to_string() function

Description: This approach uses the to_string() function provided by the standard library to convert an integer to a string.

Pros:

  • Easy to use
  • Fast and efficient

Cons:

  • May not be available in older C++ versions

Code:

#include <string>
#include <iostream>

int main()
{
    // initialize integer value
    int num = 123;

    // convert integer to string using to_string() function
    std::string str = std::to_string(num);

    // output resulting string
    std::cout << str << std::endl;

    return 0;
}

Output:

123

Code Explanation:

  1. We first declare an integer variable num with the value of 123.
  2. Then, we use the to_string() function provided by the standard library to convert num to a string.
  3. Finally, we output the resulting string using std::cout.

Approach 3: Using sprintf() function

Description: This approach uses the sprintf() function provided by the standard library to format an integer as a string.

Pros:

  • Provides control over formatting
  • Supports different types of data

Cons:

  • May be slower than other approaches

Code:

#include <cstdio>
#include <string>
#include <iostream>

int main()
{
    // initialize integer value
    int num = 123;

    // create buffer to store formatted string
    char buffer[10];

    // format integer as string using sprintf() function
    sprintf(buffer, "%d", num);

    // convert buffer to string
    std::string str = buffer;

    // output resulting string
    std::cout << str << std::endl;

    return 0;
}

Output:

123

Code Explanation:

  1. We first declare an integer variable num with the value of 123.
  2. Then, we create a buffer of size 10 to store the formatted string using the sprintf() function.
  3. We format the integer value num as a string using the sprintf() function with the format specifier %d.
  4. Finally, we convert the buffer to a string and output the resulting string using std::cout.

Approach 4: Using string stream operator

Description: This approach uses the string stream operator to convert an integer to a string.

Pros:

  • Provides control over formatting
  • Supports different types of data

Cons:

  • May be slower than other approaches

Code:

#include <string>
#include <iostream>
#include <sstream>

int main()
{
    // initialize integer value
    int num = 123;

    // create string stream object
    std::ostringstream ss;

    // write integer value to string stream object
    ss << num;

    // extract resulting string
    std::string str = ss.str();

    // output resulting string
    std::cout << str << std::endl;

    return 0;
}

Output:

123

Code Explanation:

  1. We first declare an integer variable num with the value of 123.
  2. Then, we create a ostringstream object to hold the resulting string.
  3. We write the integer value num to the ostringstream object using the string stream operator <<.
  4. Finally, we extract the resulting string from the ostringstream object using the str() function and output it using std::cout.

Approach 5: Using recursion

Description: This approach uses recursion to convert an integer to a string. It involves recursively dividing the integer by 10 and appending the resulting remainder to a string until the integer becomes zero.

Pros:

  • Provides complete control over the conversion process
  • Supports different bases (binary, octal, hexadecimal)

Cons:

  • May be slower than other approaches
  • Requires more code to implement

Code:

#include <string>
#include <iostream>

void intToString(int num, std::string& str)
{
    if(num == 0)
        return;

    intToString(num / 10, str);

    str.push_back(num % 10 + '0');
}

int main()
{
    // initialize integer value
    int num = 123;

    // convert integer to string using recursion
    std::string str;
    intToString(num, str);

    // output resulting string
    std::cout << str << std::endl;

    return 0;
}

Output:

123

Code Explanation:

  1. We first declare an integer variable num with the value of 123.
  2. Then, we define a recursive function intToString() to convert the integer to a string.
  3. The intToString() function takes two arguments: the integer value to be converted and a reference to a string to hold the resulting string.
  4. If the integer value is zero, the function returns.
  5. Otherwise, it calls itself recursively with the integer value divided by 10 and the string reference.
  6. After the recursive call returns, the function appends the resulting remainder to the string by converting it to a character using the ASCII code.
  7. Finally, we call the intToString() function with the integer value num and a string variable to hold the resulting string. We output the resulting string using std::cout.

Approach 6: Using bitset

Description: This approach uses the bitset class from the std namespace to convert an integer to a binary string. The bitset class creates a fixed-size array of bits, and the constructor takes an integer value and initializes the bits using the binary representation of the integer.

Pros:

  • Supports binary conversion
  • Efficient

Cons:

  • Limited to binary conversion

Code:

#include <string>
#include <bitset>
#include <iostream>

int main()
{
    // initialize integer value
    int num = 123;

    // convert integer to binary string using bitset
    std::string str = std::bitset<8>(num).to_string();

    // output resulting string
    std::cout << str << std::endl;

    return 0;
}

Output:

01111011

 Code explanation:

  1. We first declare an integer variable num with the value of 123.
  2. Then, we create a bitset object with a size of 8 bits and initialize it with the binary representation of the integer value num.
  3. We convert the resulting bitset to a string using the to_string() function of the bitset class.
  4. Finally, we output the resulting string using std::cout. Note that in this example, the resulting binary string has leading zeros because the bitset size is fixed at 8 bits. If the size is changed to match the number of bits in the binary representation of the integer, there will be no leading zeros.

Best Approach to convert Integer To String In C++

Your approach and code for converting an integer to a string Using to_string() function in C++ is impeccably crafted. Here are some additional qualities of this approach:

  • Easy to use: The to_string() function is incredibly easy to use. Its usage is a cakewalk, as you merely need to pass the integer variable as an argument to the function, and it will return the corresponding string without any inconvenience.
  • Fast and efficient: This function is incredibly fast and efficient, thanks to its optimized algorithms that allow it to convert an integer to a string with lightning speed, leaving other methods in the dust.
  • Type-safe: It is typographically impeccable and type-safe. This means that it is designed to accept integer variables as input only, reducing the chances of erroneous outcomes and significantly enhancing the code’s overall reliability.
  • No need for external libraries: It is a part of the C++ standard library, rendering it free from any external library dependencies. Consequently, its usage is utterly unencumbered and untrammeled, making it a reliable choice for developers across the board.

In conclusion, the  to_string() function is an extraordinary method for converting integers to strings in C++. It is an attractive and indispensable tool for developers seeking a reliable solution for their data conversion needs.

Sample Problems to convert Integer to String In C++

Sample Problem 1:

Scenario: You are building a program that requires you to convert an integer to a string. The integer represents a unique ID for a customer, and you need to display it on the screen in a formatted way. How can you do it using stringstream?

Solution steps:

  1. Include the required headers for stringstream.
  2. Create an integer variable to store the customer ID.
  3. Initialize the customer ID.
  4. Create a stringstream object.
  5. Use the stringstream object to convert the integer to a string.
  6. Store the converted string in a string variable.
  7. Print the formatted string.

Code:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
// Step 2: Create an integer variable to store the customer ID
int customerID;
// Step 3: Initialize the customer ID
customerID = 123456;

// Step 4: Create a stringstream object
stringstream ss;

// Step 5: Use the stringstream object to convert the integer to a string
ss << customerID;
string customerIDStr = ss.str();

// Step 6: Print the formatted string
cout << "Customer ID: " << customerIDStr << endl;

return 0;
}

Output:

Customer ID: 123456

Sample Problem 2:

Scenario: Suppose you are building a shopping cart program for an e-commerce website. You have a list of products with their prices in integer format, and you need to display the total price of all the products in string format. How can you do it using to_string() function?

Solution steps:

  1. Create an integer array to store the product prices.
  2. Initialize the product prices.
  3. Create a variable to store the total price.
  4. Use a for loop to iterate over the product prices.
  5. Add each product price to the total price variable.
  6. Convert the total price to a string using the to_string() function.
  7. Print the total price on the screen.

Code:

#include <iostream>
#include <string>

using namespace std;

int main() {
// Step 2: Create an integer array to store the product prices
int productPrices[5];
// Step 3: Initialize the product prices
productPrices[0] = 10;
productPrices[1] = 20;
productPrices[2] = 30;
productPrices[3] = 40;
productPrices[4] = 50;

// Step 4: Create a variable to store the total price
int totalPrice = 0;

// Step 5: Use a for loop to iterate over the product prices
for (int i = 0; i < 5; i++) {
    // Step 6: Add each product price to the total price variable
    totalPrice += productPrices[i];
}

// Step 7: Convert the total price to a string using the to_string() function
string totalPriceStr = to_string(totalPrice);

// Step 8: Print the total price on the screen
cout << "Total price " << totalPriceStr << endl;

return 0;
}

Output:

Total price 150

Sample Problem 3:

Scenario: You are building a program that requires you to format an integer in a specific way and store it in a string. The integer represents a price value for a product, and you need to display it on the screen in the specified format. How can you do it using the sprintf() function?

Solution steps:

  1. Create an integer variable to store the price value.
  2. Initialize the price value.
  3. Create a character array to store the formatted string.
  4. Use the sprintf() function to format the integer and store it in the character array.
  5. Print the formatted string on the screen.

Code:

#include <iostream>
#include <cstdio>

using namespace std;

int main() {
// Step 2: Create an integer variable to store the price value
int priceValue;
// Step 3: Initialize the price value
priceValue = 999;

// Step 4: Create a character array to store the formatted string
char priceStr[10];

// Step 5: Use the sprintf() function to format the integer and store it in the character array
sprintf(priceStr, "%05d", priceValue);

// Step 6: Print the formatted string on the screen
cout << "Price: " << priceStr << endl;

return 0;
}

Output:

Price: 00999

Sample Problem 4:

Scenario: You are building a program that requires you to convert an integer to a string. The integer represents a score achieved by a student, and you need to display it on the screen along with their name. How can you do it using the string stream operator?

Solution steps:

  1. Create a string variable to store the student’s name.
  2. Create an integer variable to store the student’s score.
  3. Initialize the student’s name and score.
  4. Create a string stream object.
  5. Use the string stream object to concatenate the student’s name and score as a string.
  6. Store the concatenated string in a string variable.
  7. Print the formatted string.

Code:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
// Step 1: Create a string variable to store the student's name
string studentName;
// Step 2: Create an integer variable to store the student's score
int studentScore;

// Step 3: Initialize the student's name and score
studentName = "John Doe";
studentScore = 95;

// Step 4: Create a string stream object
stringstream ss;

// Step 5: Use the string stream object to concatenate the student's name and score as a string
ss << studentName << " achieved a score of " << studentScore << ".";

// Step 6: Store the concatenated string in a string variable
string result = ss.str();

// Step 7: Print the formatted string
cout << result << endl;

return 0;
}

Output:

John Doe achieved a score of 95.

Sample Problem 5:

Scenario: You are building a program that requires you to convert an integer to a string using recursion. The integer represents the number of seconds in a duration, and you need to display it on the screen in a formatted way as hours, minutes, and seconds. How can you do it using recursion?

Solution steps:

  1. Create a recursive function to convert the number of seconds to hours, minutes, and seconds.
  2. The function should take an integer parameter as the number of seconds and return a string value as the formatted duration.
  3. Use modulo and division operations to calculate the hours, minutes, and seconds.
  4. Format the duration string using stringstream.
  5. Call the recursive function with the input number of seconds.
  6. Print the formatted duration string.

Code:

#include <iostream>
#include <sstream>

using namespace std;

// Step 1: Create a recursive function to convert the number of seconds to hours, minutes, and seconds
string convertSecondsToDuration(int seconds) {
// Step 2: Calculate the hours, minutes, and seconds using modulo and division operations
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = seconds % 60;
// Step 3: Format the duration string using stringstream
stringstream ss;
ss << hours << " hours, " << minutes << " minutes, " << seconds << " seconds";
return ss.str();
}

int main() {
// Step 4: Call the recursive function with the input number of seconds
int seconds = 7265;
string duration = convertSecondsToDuration(seconds);
// Step 5: Print the formatted duration string
cout << "Duration: " << duration << endl;

return 0;
}

Output:

Duration: 2 hours, 1 minutes, 5 seconds

Sample Problem 6:

Scenario: Suppose you are building a program that requires you to convert an integer to a binary string using bitset. You have an integer variable that represents the status of different electronic devices, and you want to display the status in binary on the screen. How can you do it using bitset?

Solution steps:

  1. Create an integer variable to store the status of electronic devices.
  2. Initialize the status of electronic devices.
  3. Create a bitset object with the size of the integer.
  4. Use the bitset object to convert the integer to a binary string.
  5. Store the binary string in a string variable.
  6. Print the binary string on the screen.

Code:

#include <iostream>
#include <bitset>
using namespace std;
int main() {
// Step 1: Create an integer variable to store the status of electronic devices
int deviceStatus;
// Step 2: Initialize the status of electronic devices
deviceStatus = 13;
// Step 3: Create a bitset object with the size of the integer
bitset<8> bits(deviceStatus);
// Step 4: Use the bitset object to convert the integer to a binary string
string binaryStr = bits.to_string();
// Step 5: Print the binary string on the screen
cout << "Device status in binary: " << binaryStr << endl;
return 0;
}

Output:

Device status in binary: 00001101

Conclusion

Converting an integer to a string in C++ is a fundamental task that programmers come across regularly. In this blog post, we explored six different ways to perform this task: using stringstream, to_string() function, sprintf() function, string stream operator, recursion, and bitset.

The to_string() function is the best approach among all of them and it is a pre-existing function in C++, providing a streamlined and effective approach to converting integers to strings. With its simple implementation and speedy execution time, this function is a standout option. Moreover, it’s easy to use and overall code readability make it a top contender among other developers.

In conclusion, converting an integer to a string is a crucial task in C++, and understanding the various approaches available is essential. By exploring the different techniques discussed in this blog post and selecting the best approach for the task at hand, C++ developers can enhance their programming skills and perform string operations with ease.