std::stringstream 是 C++ 标准库中的一个类,它位于 <sstream> 头文件中
以下是使用 std::stringstream 进行数据格式化的示例:
#include<iostream>#include <iomanip> // 包含设置输出格式的函数,如 setw, setprecision 等#include <sstream>#include<string>int main() { int a = 123; float b = 456.789f; std::stringstream ss; // 设置宽度为 10,右对齐,用空格填充 ss<< std::setw(10)<< std::right << a << "\n"; // 设置浮点数精度为 2 位小数 ss<< std::fixed<< std::setprecision(2); // 设置宽度为 10,左对齐,用空格填充 ss<< std::setw(10)<< std::left << b << "\n"; std::string formatted_output = ss.str(); std::cout<< formatted_output; return 0;}这段代码将输出:
123456.79在这个示例中,我们使用了 std::setw 和 std::right/std::left 来设置输出宽度和对齐方式。同时,我们使用了 std::fixed 和 std::setprecision 来设置浮点数的精度。最后,我们使用 ss.str() 方法获取格式化后的字符串。


