C++ iomanip意外影响ctime函数输出
我的目标是使用C++ iomanip意外影响ctime函数输出,c++,C++,我的目标是使用设置大约50个空格的宽度,并让打印日期和时间,但是这样做时无法按预期工作。我以前的输出使用了这种方式,输出字符,效果很好,所以我不确定我现在做错了什么 // Example program #include <iostream> #include <string> #include <ctime> #include <iomanip> using namespace std; void dateTime(){ time_t
设置大约50个空格的宽度,并让
打印日期和时间,但是这样做时
无法按预期工作。我以前的输出使用了
这种方式,输出字符,效果很好,所以我不确定我现在做错了什么
// Example program
#include <iostream>
#include <string>
#include <ctime>
#include <iomanip>
using namespace std;
void dateTime(){
time_t now = time(0);
tm* dt = localtime(&now);
cout << setfill(' ') << setw(56) << left << 1900 + dt->tm_year << "/" << 1 + dt->tm_mon << "/" << dt->tm_mday << ", " << dt->tm_hour << ":" << dt->tm_min << " |" << endl;
}
int main()
{
dateTime();
}
预期输出(正确):
您可以定义自己的
ignore\u操纵器
stream对象,这将阻止从iomanip
操纵输出。这是我在中的实现
精简实施:
struct ignore_manipulator
{
std::string _str;
ignore_manipulator(const std::string& str)
: _str(str)
{
}
auto& operator=(const std::string& str)
{
_str = str;
return *this;
}
operator const T&() const noexcept
{
return _str;
}
auto begin() const noexcept
{
return std::begin(_str);
}
auto end() const noexcept
{
return std::end(_str);
}
};
template <typename T>
auto operator<<(std::ostream& o, const ignore_manipulator& im)
{
// `o.put` ignores manipulators.
for(const auto& c : im) o.put(c);
return o;
}
struct ignore\u操纵器
{
std::string _str;
忽略_操纵器(常量std::string和str)
:_str(str)
{
}
自动运算符=(常量std::string和str)
{
_str=str;
归还*这个;
}
运算符常量T&()常量noexcept
{
返回_str;
}
自动开始()常量noexcept
{
返回标准::开始(_str);
}
自动结束()常量noexcept
{
返回标准::结束(_str);
}
};
模板
自动运算符问题在于std::setw
只影响一个输出的字段宽度,而不影响组成您关心的日期/时间的整个输出组。幸运的是,该标准提供了一种非常干净的方法来处理这个问题:std::put_time
操纵器创建一个包含您关心的字段的单一结果,因此您可以使用它格式化输出,如下所示:
// Example program
#include <iostream>
#include <string>
#include <ctime>
#include <iomanip>
using namespace std;
void dateTime() {
time_t now = time(0);
tm* dt = localtime(&now);
std::cout << std::setw(56) << std::put_time(dt, "%Y/%m/%d, %H:%M") << "|";
}
int main()
{
dateTime();
}
2016/01/06, 17:48 |
您需要在问题中同时包含代码和预期输出(以及您得到的不正确输出),而不是外部链接。@KeithThompson better?better?现在更是如此。我更新了你的问题,包括完整的程序以及实际和预期的输出,都在问题的主体中,没有外部链接。@KeithThompson哦,好吧,看起来好多了,下次我会记住的,谢谢。我希望输出被操纵,我想我已经解决了我的问题。谢谢,我几乎是在回答啊哈,我不知道你可以有多个转换说明符在一个调用的put_时间。
// "hello" won't be affected by previous manipulators.
cout << setfill(' ') << setw(56) << ignore_manipulator("hello") << "\n";
// Example program
#include <iostream>
#include <string>
#include <ctime>
#include <iomanip>
using namespace std;
void dateTime() {
time_t now = time(0);
tm* dt = localtime(&now);
std::cout << std::setw(56) << std::put_time(dt, "%Y/%m/%d, %H:%M") << "|";
}
int main()
{
dateTime();
}
2016/01/06, 17:48 |