【C编程】去掉显示时间的换行符!

  C语言中char *ctime(const time_t *time);函数将参数timep 所指的time_t 结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果以字符串形态返回。此函数已经由时区转换成当地时间,输出4个字节日期字符串格式为"Wed Jun 30 21 :49 :08 2020\n"。
  为了去掉输出日期中的换行符,如下编程:

/*=========================================
* Copyright (c) 2020, 逐风墨客
* All rights reserved.
* 
* 文件名称:study_nontime.c
* 运行环境:Linux操作系统
* 功能描述:去掉显示时间的换行符!
=========================================*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // 调用sleep()函数
#include <time.h>

const char *show_realtime(time_t t); 

int main(void)
{
  time_t t = 0;
  
  printf("The current time is : %s\n", show_realtime(t));
  sleep(5);
  printf("The current time after 5 seconds is : %s\n", show_realtime(t));
  return 0;  
}

/*******************************************
* 函数介绍:const char *show_realtime(time_t t)
* 输入参数:t-时间种子
* 输出参数:无
* 返回值:buf-不带换行符的字符串时间
*******************************************/
const char *show_realtime(time_t t)
{
  static char buf[32];
  char *p = NULL;

  time(&t);
  strcpy(buf, ctime(&t));
  p = strchr(buf, '\n');
  *p = '\0';
  return buf;
}

  程序运行结果:


程序运行结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容