格式化:如何将1转换为“01”,将2转换为“02”,将3转换为“03”,依此类推

问题描述 投票:2回答:3

以下代码以时间格式输出值,即如果它是1:50 pm和8秒,它将输出为01:50:08

cout << "time remaining: %02d::%02d::%02" << hr << mins << secs;

但我想要做的是(a)将这些int转换为char / string(b),然后将相同的时间格式添加到其对应的char / string值。

我已经实现了(a),我只想实现(b)。

EG

    char currenthour[10] = { 0 }, currentmins[10] = { 0 }, currentsecs[10] = { 0 };

    itoa(hr, currenthour, 10);
    itoa(mins, currentmins, 10);
    itoa(secs, currentsecs, 10);

现在,如果我输出'currenthour','currentmins'和'currentsecs',它将输出相同的示例时间,1:50:8,而不是01:50:08。

想法?

c++ string datetime int itoa
3个回答
4
投票

如果你不介意开销,你可以使用std::stringstream

#include <sstream>
#include <iomanip>

std::string to_format(const int number) {
    std::stringstream ss;
    ss << std::setw(2) << std::setfill('0') << number;
    return ss.str();
}

3
投票

从你的comment

“我认为,使用%02是标准的c / c ++练习。我错了吗?”

是的,你错了。 c / c ++也不是一件事,这些是不同的语言。

C ++ std::cout不支持printf()格式化字符串。你需要的是setw()setfill()

cout << "time remaining: " << setfill('0')
     << setw(2) <<  hr << ':' << setw(2) << mins << ':' << setw(2) << secs;

如果你想要一个std::string作为结果,你可以用同样的方式使用std::ostringstream

std::ostringstream oss;
oss << setfill('0')
     << setw(2) <<  hr << ':' << setw(2) << mins << ':' << setw(2) << secs;
cout << "time remaining: " << oss.str();

还有一个可用的增强库boost::format,类似于格式字符串/占位符语法。


0
投票

作为其他答案中建议的IOStreams的替代方法,您还可以使用安全的printf实现,例如fmt library

fmt::printf("time remaining: %02d::%02d::%02d", hr, mins, secs);

它支持printf和类似Python的格式字符串语法,其中可以省略类型说明符:

fmt::printf("time remaining: {:02}::{:02}::{:02}", hr, mins, secs);

免责声明:我是fmt的作者。

© www.soinside.com 2019 - 2024. All rights reserved.