c++ - 数字到固定长度的字符串

标签 c++ string

标准库中是否有一个函数可以像 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/

相关文章:

c++ - 在 c++ 中的 map<string, <vector<string>> 中查找 vector 中的值

C++ 按需创建

c++ - 将空源文件添加到 STATIC 库的原因?

java - Hashtable<String, Object> 找不到字符串

sql - 如何删除文本的第一个和最后一个字符?

c++ - 比较位(一次一个位置)

c - 根据第 n 项对数字进行排序

c++ - 在 C++ 中哪些操作不能抛出异常?

c++ - 通过指向指针的指针访问结构元素的地址

c++ - 显式初始化成员是什么意思?