在C++中,ostringstream是一个非常有用的类,它允许将各种数据类型转换为字符串。以下是一些使用ostringstream的技巧:
int num = 10;
ostringstream oss;
oss << num;
string str = oss.str(); // 将int类型转换为string类型
string str1 = "Hello";
string str2 = "World";
ostringstream oss;
oss << str1 << " " << str2;
string result = oss.str(); // 连接字符串
int num = 10;
float price = 3.14;
ostringstream oss;
oss << "The number is " << num << " and the price is $" << fixed << setprecision(2) << price;
string result = oss.str(); // 格式化输出字符串
ostringstream oss;
oss << "Hello";
oss.clear(); // 清空对象状态
oss << "World";
string result = oss.str(); // 输出结果为"World"
这些是一些使用ostringstream的常见技巧,可以根据具体的需求进行灵活应用。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:C++ ostringstream的性能优化技巧有哪些