【问题标题】:Printing a date in DD\MM\YYYY format using only iostream?仅使用 iostream 以 DD\MM\YYYY 格式打印日期?
【发布时间】:2014-07-12 19:01:36
【问题描述】:

我有一个类代表一个带有 3 个无符号整数字段的日期 -

日、月、年。

我想以 DD\MM\YYYY 格式打印到控制台,这意味着如果添加前导零 必须的。

有什么方法只能用“iostream”来实现吗?

我知道使用“iomanip”可以通过“fill”和“setw”轻松完成。

还有,如何打印流浪(\)字符?

谢谢

【问题讨论】:

  • 为什么你的斜线是左撇子?

标签: c++ printing cout


【解决方案1】:
void PrintDate(unsigned day, unsigned month, unsigned year)
{
  std::stringstream stream;
  stream << std::setw(2) << std::setfill('0') << day << "/" << std::setw(2) << std::setfill('0') << month << "/" << std::setw(4) << year;
  std::cout << stream.str() << std::endl;
}

编辑:

void PrintDate(unsigned day, unsigned month, unsigned year)
{
  std::stringstream stream;

  if (day < 10)
  {
    stream << "0";
  }

  stream << day << "/";

  if (month < 10)
  {
    stream << "0";
  }

  stream << month << "/" << year;

  std::cout << stream.str() << std::endl;
}

【讨论】:

  • 谢谢,但正如我所提到的 - 不使用 IOMANIP 库,仅使用 IOSTREAM(如果可能的话)。
  • 您为什么要这样做?是的,你可以使用 if 语句,但看起来很乱。
  • 我知道我的朋友,这是我们的作业说明。去搞清楚。我会尝试您在编辑后发布的建议代码,谢谢。
  • 别担心,让你的老师知道他们在问愚蠢的问题,并且仍然停留在现在冗余的旧代码世界中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多