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 namednumber
and initializes it with the value 123.std::stringstream ss;
: Creates an objectss
of typestd::stringstream
, which is used for string stream operations.ss << number;
: Uses the<<
operator to insert the value ofnumber
into thestd::stringstream
objectss
. This converts the integernumber
into a string and stores it inss
.std::string str = ss.str();
: Calls thestr()
method on thestd::stringstream
objectss
to retrieve the string representation of the content stored inss
and assigns it to thestd::string
variablestr
.std::cout << "String representation of number: " << str << std::endl;
: Prints the string representation of thenumber
variable usingstd::cout
.
This program demonstrates how to convert an integer to a string using a std::stringstream
object in C++.