stringstream是一个用于字符串操作的类,可以将各种数据类型转换为字符串,也可以将字符串转换为各种数据类型。下面是一些stringstream的常见用法:
#include <iostream>
#include <sstream>
int main() {
int num = 123;
double value = 3.14;
std::stringstream ss;
ss << "Integer: " << num << ", Double: " << value;
std::string str = ss.str();
std::cout << str << std::endl;
return 0;
}
#include <iostream>
#include <sstream>
int main() {
std::string str = "123 3.14";
int num;
double value;
std::stringstream ss(str);
ss >> num >> value;
std::cout << "Integer: " << num << ", Double: " << value << std::endl;
return 0;
}
#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
ss << "Hello, World!";
std::cout << ss.str() << std::endl;
ss.str("");
std::cout << ss.str() << std::endl; // Output is empty
return 0;
}
#include <iostream>
#include <sstream>
#include <iomanip>
int main() {
double value = 3.14159;
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << value;
std::string str = ss.str();
std::cout << "Formatted Value: " << str << std::endl;
return 0;
}
以上是stringstream的一些常见用法,可以根据实际需求灵活运用stringstream类进行字符串操作。