请耐心等待,因为我对 C 编程还很陌生。当我运行此代码时:
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
while (1) {
time_t mytime;
mytime = time(NULL);
printf("%s Hello world\n", ctime(&mytime));
sleep(1);
}
return 0;
}
输出总是如下所示:
Wed Jan 18 02:32:32 2017
Hello world
Wed Jan 18 02:32:33 2017
Hello world
Wed Jan 18 02:32:34 2017
Hello world
我想要的是这样的:
Wed Jan 18 02:32:32 2017 Hello world
Wed Jan 18 02:32:33 2017 Hello world
Wed Jan 18 02:32:34 2017 Hello world
我怎样才能做到这一点?
注意:
如果我从 printf("%s Hello world\n", ctime(&mytime));
中删除 \n
,结果将如下所示:
Wed Jan 18 02:38:29 2017
Hello worldWed Jan 18 02:38:30 2017
Hello worldWed Jan 18 02:38:31 2017
Hello worldWed Jan 18 02:38:32 2017
Hello worldWed Jan 18 02:38:33 2017
最佳答案
ctime
函数将返回一个指向以换行符结尾的字符串的指针。
来自man page :
The call
ctime(t)
is equivalent toasctime(localtime(t))
. It converts the calendar time t into a null-terminated string of the form "Wed Jun 30 21:49:08 1993\n"
如果不需要换行符,则需要在打印之前保存指针并删除换行符。
char *t = ctime(&mytime);
if (t[strlen(t)-1] == '\n') t[strlen(t)-1] = '\0';
printf("%s Hello world\n", t);
关于c - 如何删除C程序中 "ctime"之后的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705537/