Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the string returned by ctime() contain a line feed?

Tags:

c++

c

string

time

std

Why does the string returned by ctime() have a line feed (0x0A) as its final character? For example, this code:

#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; } 

...produces the following output:

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

It's not a big deal; I can strip the final byte from the string, but why does ctime() put it there in the first place?

like image 900
bythescruff Avatar asked Oct 23 '13 14:10

bythescruff


2 Answers

According to the C99 Rationale, the new line exists because of existing practice, which I think it's the same as saying for historical reasons.

Rationale for International Standard — Programming Languages — C §7.23.3.1 The asctime function

Although the name of this function suggests a conflict with the principle of removing ASCII dependencies from the Standard, the name was retained due to prior art. For the same reason of existing practice, a proposal to remove the newline character from the string format was not adopted.

This talks about asctime, but since ctime is equivalent to asctime(localtime(timer)), so the same rule applies.

like image 144
Yu Hao Avatar answered Sep 18 '22 23:09

Yu Hao


The POSIX Standard claims historical compatibility:

[asctime] is included for compatibility with older implementations ... Applications should use strftime() to achieve maximum portability.

Given that it was included for compatibility with older implementations, it's reasonable to assume that some older library implemented asctime with a newline at the end

like image 23
SheetJS Avatar answered Sep 19 '22 23:09

SheetJS