String streams in C++ provide a powerful way to manipulate strings and perform conversions between strings and other data types. They combine the flexibility of strings with the functionality of input/output streams.
A string stream is an in-memory stream that uses a string as its source or destination. It's part of the <sstream>
header and offers three main classes:
istringstream
: For input operationsostringstream
: For output operationsstringstream
: For both input and output operationsString streams are particularly useful for:
#include <sstream>
#include <string>
#include <iostream>
int main() {
int number = 42;
std::ostringstream oss;
oss << number;
std::string str = oss.str();
std::cout << "Number as string: " << str << std::endl;
return 0;
}
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::string input = "10 20 30";
std::istringstream iss(input);
int a, b, c;
iss >> a >> b >> c;
std::cout << "Sum: " << (a + b + c) << std::endl;
return 0;
}
clear()
and str("")
methods.istringstream
for input-only operations and ostringstream
for output-only operations when possible.While string streams are versatile, they may have a slight performance overhead compared to direct string manipulation. For performance-critical applications, consider using C++ Performance Optimization techniques.
By mastering string streams, you'll enhance your ability to handle complex string operations and data conversions in C++, making your code more flexible and powerful.