stringstream stream number to string

#include <iostream>
#include <sstream>

int main() {
    int number = 123;
    std::stringstream ss;
    ss << number;
    std::string str = ss.str();
    std::cout << "String representation of number: " << str << std::endl;
    return 0;
}

Explanation:

  • #include <iostream> and #include <sstream>: Includes the necessary libraries for input-output operations and string streaming.
  • int number = 123;: Declares an integer variable named number and initializes it with the value 123.
  • std::stringstream ss;: Creates an object ss of type std::stringstream, which is used for string stream operations.
  • ss << number;: Uses the << operator to insert the value of number into the std::stringstream object ss. This converts the integer number into a string and stores it in ss.
  • std::string str = ss.str();: Calls the str() method on the std::stringstream object ss to retrieve the string representation of the content stored in ss and assigns it to the std::string variable str.
  • std::cout << "String representation of number: " << str << std::endl;: Prints the string representation of the number variable using std::cout.

This program demonstrates how to convert an integer to a string using a std::stringstream object in C++.