标准库中是否有一个函数可以像 std::to_string
一样工作,但具有固定长度?
std::cout << formatted_time_string << ":" << std::to_string(milliseconds) << " ... other stuff" << std::endl;
在上面的示例中,毫秒的范围是 1 到 3 位数字,因此输出格式不正确。
我知道还有很多其他选项可以如何执行此操作(例如 sprintf
、计算长度等),但是最好有一个内联选项。
最佳答案
您可以使用 std::setw()
函数设置在输出操作期间使用的字段。要保持正确对齐,您可以使用 std::setfill()
:
#include <iomanip> // for std::setw and std::setfill
std::cout << std::setfill('0') << std::setw(3) << formatted_time_string << ":" << std::to_string(milliseconds) << " ... other stuff" << std::endl;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
如果milliseconds
是一个float
,你也可以使用std::setprecision
:
#include <iomanip> // for std::setprecision
std::cout << formatted_time_string << ":" << std::setprecision(3) << milliseconds << " ... other stuff" << std::endl;
// ^^^^^^^^^^^^^^^^^^^^^^^
关于c++ - 数字到固定长度的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18327831/