Why does the string returned by ctime () contain the string?

Why ctime() string returned by ctime() have the string ending ( 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 does not matter; I can remove the final byte from the string, but why ctime() put it there first?

+48
c ++ c string time std
Oct 23 '13 at 14:06 on
source share
6 answers

According to the C99 Justification, the new line exists because of existing practice, which, I think, is the same as for historical reasons.

Justification for the International Standard - Programming Languages ​​- C Β§7.23.3.1 asctime Function

Although the name of this function is in conflict with the principle of removing ASCII dependencies from the Standard, the name was retained due to the prior art. For the same reason as existing practice, the proposal to remove the newline character from the line format was not accepted.

This indicates asctime , but since ctime equivalent to asctime(localtime(timer)) , the same rule applies.

+46
Oct 23 '13 at 14:15
source share

POSIX Standard claims historical compatibility:

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

Given that it was included for compatibility with older implementations, it is reasonable to assume that some older library implemented asctime with a new line at the end

+7
Oct 23 '13 at 14:20
source share

This behavior is required as defined in the specification 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)) 
+4
Oct 23 '13 at 14:10
source share

This may be because initially it was necessary to execute the program date on Unix. (Maybe a new line for the shell)? Therefore, for historical reasons.

+4
Oct 23 '13 at 14:16
source share

If you need your own format (one without a new line), use strftime() . The format string "%c" should contain approximately the same format, but without a new line.

+3
Oct 23 '13 at 14:11
source share

The asctime() man page mentions (but does not emphasize) that the returned string has a terminating newline before the terminating null character. Why this information is not present on the ctime page is a mystery.

0
Sep 18 '14 at 1:06 on
source share



All Articles