C++ Win32 通过 to_wstring 将零填充到 int

标签 c++ winapi wstring

我正在尝试学习 C++ Win32。我为游戏环境构建了一个计时器类。典型的游戏计时器,效果很好。我有这个函数,我想用它来显示当前的游戏时间。

std::wstring Time::DisplayGameTime()
{
    std::wstring Label = L"Current Time: ";

    std::wstring daysText = L" " + std::to_wstring(Days()); //Returns int
    std::wstring monthsText = L", " + std::to_wstring(Months()); //Returns int
    std::wstring yearsText = L", " + std::to_wstring(Years()); // Returns int
    std::wstring hoursText = L" " + std::to_wstring(Hours()); // Returns int
    std::wstring minutesText = L" : " + std::to_wstring(Minutes()); // Returns int

    std::wstring message = Label + daysText + monthsText + yearsText + hoursText + minutesText;
    return message;
}

这也很好用,除了分钟整数在达到 10 之前只打印一位数字。我想在它前面填充一个前导零,就像在普通时钟中看到的那样。由于我使用的是 std::to_wstring,因此我无法像在 swprintf_s 缓冲区中那样使用格式说明符。我试图找出如何使用 wstringstream 来实现此目的,但我尝试过的方法都不起作用。

目标是稍后使用此函数转换为 LPCWSTR,以便 DrawText 显示到窗口。

最佳答案

您可以使用传统的命令式“暴力”方式来解决此问题:

int DaysVal = Days();
std::wstring W = (DaysVal < 10 ? L"0" : L"") + std::to_wstring(DaysVal);

或者..使用std::stringstreamstd::setwstd::setfill (来自<iomanip>)。

std::wstringstream WS;
WS << std::setw(2) << std::setfill(L'0') << Days();
std::wstring W = WS.str();

PS:功能来自 <iomanip>还致力于std::cout和其他流,所以 std::(w)stringstream对于 I/O 来说是不必要的!

编辑:如果有人正在寻找利用 snprintf() 的解决方案:

char CB[128];
std::snprintf(CB, sizeof(CB), "%.*i", NumDigits, Num);

使用精度 ( %.*i ) 优于使用宽度 ( %*i ),因为第二个精度对字符总数而不是位数进行操作!

编辑(2):为了面向 future ,我还提供了一个使用 std::format() 的解决方案:

我还没玩过{fmt}太久了,所以我不知道如何达到与 printf() 相同的结果。现在,它应该足够了(但预计负数会少一位数):

std::wstring W = fmt::format(L"{:+0{}}", Num, NumDigits);

关于C++ Win32 通过 to_wstring 将零填充到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71020244/

相关文章:

c++ - 解析数据的正则表达式

c++ - 为什么 getline() 不读取文本文件中的所有内容?

c++ - 我的代码在 Windows XP 上不工作

c++ - 结合 std::wstring 和函数

c++ - 在 std::wstring 中查找方法

c++ - 有没有办法在递归中使用指针来查找数组的最小值?

c++ - 使用用户定义文字的成员时出现编译错误

windows - 为什么在使用 OS 和磁盘缓冲区写入文件后读取操作要快得多?

c - 小写windows.h和大写Windows.h的区别?

c++ - 我如何在 C++ 中处理日文字符?