阅读量:118
std::ostringstream 是 C++ 标准库中的一个非常有用的类,它允许你使用流操作符 << 来构建字符串。以下是如何使用 std::ostringstream 来处理字符串流的一些基本示例:
示例 1: 使用 std::ostringstream 拼接字符串
#include
#include
#include
int main() {
std::ostringstream oss;
oss << "Hello, " << "World!" << std class="hljs-comment">// 注意 std::ends 用于添加空行
std::string str = oss.str(); // 使用 str() 方法获取构建好的字符串
std::cout << str class="hljs-keyword">return 0;
}
示例 2: 在 std::ostringstream 中格式化字符串
你可以使用流操作符 << 来格式化字符串,就像在 printf 中一样。
#include
#include
#include
int main() {
int a = 10;
double b = 3.14;
std::ostringstream oss;
oss << "The value of a is "<< a class="hljs-string">" and the value of b is " << b xss=removed class="hljs-built_in">str();
std::cout << str class="hljs-keyword">return 0;
}
示例 3: 使用 std::ostringstream 进行类型转换
std::ostringstream 也可以用于不同类型之间的转换。例如,你可以将一个整数转换为字符串。
#include
#include
#include
int main() {
int a = 123;
std::ostringstream oss;
oss << a xss=removed class="hljs-built_in">str();
std::cout << "The string representation of "<< a class="hljs-string">" is " << str class="hljs-keyword">return 0;
}
示例 4: 使用 std::ostringstream 进行多个操作
你可以在一个 std::ostringstream 对象上执行多个操作,然后再获取构建好的字符串。
#include
#include
#include
int main() {
std::ostringstream oss;
oss << "The answer is " << 42 << ", which is " << (100 - 42) << ".";
std::string str = oss.str();
std::cout << str class="hljs-keyword">return 0;
}
这些示例展示了如何使用 std::ostringstream 来方便地构建和处理字符串。