【问题标题】:Why does the string returned by ctime() contain a line feed?为什么 ctime() 返回的字符串包含换行符?
【发布时间】:2013-11-01 20:46:33
【问题描述】:

为什么ctime() 返回的字符串的最后一个字符是换行符(0x0A)?例如这段代码:

#include <iostream>
#include <cstdlib>

int main(int argc, char* argv[])
{
    time_t now;
    time(&now);
    char* time_str = ctime(&now);
    std::cout << time_str << "why is this on a new line?" << std::endl;
    return 0;
}

...产生以下输出:

$ ./time.exe
Wed Oct 23 14:52:29 2013
why is this on a new line?
$ 

这没什么大不了的;我可以从字符串中去掉最后一个字节,但是为什么ctime() 把它放在首位呢?

【问题讨论】:

  • 请注意:0x0A 是换行符,而不是回车符。
  • 我之前看到过这个问题的辩论,但没有得出任何结论性的推理。这样做绝对没有明确的标准。它似乎就是它的实现方式。
  • @ShafikYaghmour 是的,这正是我所说的。它之所以存在,是因为它存在于以前的标准中,这仍然没有很好地说明它最初存在的原因。
  • 感谢您的更正和编辑;显然我工作太努力了,无法记住我的 ASCII。 :-)

标签: c++ c string time std


【解决方案1】:

按照 ISO 9899:1990 规范的定义,此行为是必需的。

7.12.3.1 The asctime function

The asctime function converts the broken-down time in the structure
pointed to by timeptr into a string in the form

         Sun Sep 16 01:03:52 1973\n\0

7.12.3.2 The ctime function

The ctime function converts the calendar time pointed to by timer to
local time in the form of a string.  It is equivalent to 

         asctime(localtime(timer))

【讨论】:

  • 我认为 OP 是在问为什么,因为标准中似乎没有提供的理由是什么。
【解决方案2】:

如果您想要自己的格式(没有换行符的格式),请改用strftime()。格式字符串"%c" 应该提供大致相同的格式,但没有换行符。

【讨论】:

    【解决方案3】:

    根据C99 Rationale,新线路的存在是现有的实践,我认为这与历史原因相同。

    Rationale for International Standard — Programming Languages — C §7.23.3.1 asctime 函数

    虽然这个函数的名字暗示了与去掉ASCII的原则有冲突 依赖于标准,由于现有技术,名称被保留。 出于与现有做法相同的原因,没有采用从字符串格式中删除换行符的建议。

    这里讲的是asctime,但是由于ctime等价于asctime(localtime(timer)),所以同样的规则适用。

    【讨论】:

      【解决方案4】:

      可能是因为最初需要执行日期 Unix 中的程序。 (所以也许是外壳的换行符)?所以可能是出于历史原因。

      【讨论】:

        【解决方案5】:

        POSIX Standard 声称具有历史兼容性:

        包含 [asctime] 是为了与旧实现兼容...应用程序应使用 strftime() 以实现最大的可移植性。

        鉴于包含它是为了与旧实现兼容,因此可以合理地假设某些旧库实现 asctime,末尾带有换行符

        【讨论】:

          【解决方案6】:

          asctime() 手册页确实提到(但没有强调)返回的字符串在终止空字符之前有一个终止换行符。为什么ctime 手册页中也没有此信息是一个谜。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-06-30
            • 1970-01-01
            • 2013-05-24
            • 1970-01-01
            • 2016-01-24
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多