为什么ctime()返回的string包含换行符?

为什么ctime()返回的string的换行符( 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? $ 

没什么大不了的; 我可以从string中ctime()最后一个字节,但为什么ctime()把它放在第一位呢?

根据C99理由,新的路线是因为现有的做法而存在的,我认为这与历史原因一样。

国际标准的理由 – 编程语言 – C§7.23.3.1asctime函数

虽然这个函数的名字与从标准中删除ASCII依赖的原理有冲突,但由于现有技术,名称被保留了下来。 出于同样的原因,现有的做法是,没有采用从string格式中删除换行符的build议。

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

POSIX标准声明了历史兼容性:

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

考虑到它是为了与旧的实现兼容而被包括在内,所以假定一些较老的库在最后用一个换行符实现asctime是合理的

这个行为是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)) 

这可能是因为最初需要在Unix中实现date程序。 (所以也许是shell的换行符)? 所以出于历史原因也许。

如果你想要自己的格式(没有换行符),请使用strftime() 。 格式string"%c"应该给你大致相同的格式,但没有换行符。

asctime()手册页提到(但不强调)返回的string在终止空字符之前有一个终止的换行符。 为什么这些信息在ctime手册页中不存在也是一个谜。