Formatting dates with stringstream

亡梦爱人 提交于 2020-02-05 05:56:08

问题


I want to avoid the usage of sprintf in my C++ code so I can use only std strings from C++, but I haven't found the way to replace it yet. I currently use sprintf to format dates and times like this:

char myDate[DATE_LENGTH]{};
sprintf(myDate, "%4d-%02d-%02d %02d:%02d:%02d", year, month, day,
        hour, minute, second);

In this way, I will get a fixed length for each integer, with leading zeros if needed.

I have searched how to replace this with stringstream, and found this:

std::ostringstream ss;
ss << std::setw(5) << std::setfill('0') << 12 << "\n";

But this only would format one of the integers. I would need to do this for each date and tiem component and then append all of them together. So to replace one line of C-style code, I would need much more new code.

Is not there any way to do better than this?


回答1:


(1) Define your own datatime class.

(2) Define the operator <<() and operator >>() for it. In these function, use std::time_put and std::time_get facet to implement.

(3) If the std::time_put and std::time_get can't satisfy your needs, you can define your own time_put/get facet by inheriting them, and other assistant facet such as date_time format manager if necessary.

PS: If you're using c++11, std::time_put::put() and std::time_get::get() may be satisfied.

Good Luck!




回答2:


There is nothing bad in using snprintf() or strftime() in a C++ application. They are fast, reliable, and they are part of the standard library. IOStreams are sometimes just too verbose to use them directly. You can always wrap the sprintf-based serializer into an iostream shell.

Another way to format date/time in C++11 without boilerplate is via put_time.



来源:https://stackoverflow.com/questions/22142372/formatting-dates-with-stringstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!