C++ Standard Library <sstream>
In C++ programming, converting between strings and numbers is a common task.
sstreamis a component in the C++ standard library that provides a convenient way to handle string streams (allowing strings to be processed like streams).
<sstream>Allows you to use strings as input/output streams, which makes it very easy to read data from strings or write data to strings.
definition
sstreamis a namespace in the C++ standard library that contains several classes for handling string streams, including:
istringstream: Used to read data from a string.ostringstream: Used to write data to a string.stringstream: yesistringstreamandostringstreamcombination, enables both read and write operations simultaneously.
Syntax
UsagesstreamThe basic syntax is as follows:
#include <sstream>
// 使用istringstream
std::istringstream iss("some data");
// 使用ostringstream
std::ostringstream oss;
// 使用stringstream
std::stringstream ss;
Example
Read data from a string
Below is a use ofistringstreamExample of reading integers and floating-point numbers from a string:
Example
#include <sstream>
int main() {
std::string data = "10 20.5";
std::istringstream iss(data);
int i;
double d;
iss >> i >> d;
std::cout << "Integer: " << i << std::endl;
std::cout << "Double: " << d << std::endl;
return 0;
}
Output result:
Integer: 10 Double: 20.5
Write data to a string
Below is a use ofostringstreamExample of writing data to a string:
Example
#include <sstream>
int main() {
std::ostringstream oss;
int i = 100;
double d = 200.5;
oss << i << " " << d;
std::string result = oss.str();
std::cout << "Resulting string: " << result << std::endl;
return 0;
}
Output result:
Resulting string: 100 200.5
Using stringstream for read and write operations
Below is a use ofstringstreamExample of performing read and write operations simultaneously:
Example
#include <sstream>
int main() {
std::string data = "30 40.5";
std::stringstream ss(data);
int i;
double d;
// Read data from stringstream
ss >> i >> d;
std::cout << "Read Integer: " << i << ", Double: " << d << std::endl;
// Write data to stringstream
ss.str(""); // Clear stringstream
ss << "New data: " << 50 << " " << 60.7;
std::string newData = ss.str();
std::cout << "New data string: " << newData << std::endl;
return 0;
}
Output result:
Read Integer: 30, Double: 40.5 New data string: New data: 50 60.7
Summary
sstreamis a very useful component in the C++ standard library, simplifying conversion between strings and basic data types. From the examples above, we can see how to useistringstream、ostringstreamandstringstreamto implement these conversions. Mastering these skills will help you handle string data more efficiently in C++ programming.