一直没弄明白在控制台下如何实现实时更新、无闪烁的时间显示,今天偶然发现回车(CR)和换行(LF)是不同的,在C语言中分别用转义字符’\r’和’\n’表示。回车的语义应该是”光标”移动到当前行的行首,而换行是”光标”移动到下一行,并没有定义一定移动到行首。这样,这里要实现的控制台下实时更新、无闪烁的小时钟就可以用相关的时间函数和回车符来完成:

#include <iostream>
#include <ctime>
using namespace std;
 
int 
main()
{
	time_t current_tm;
	const int tm_len = 50;
	char ftime[tm_len];
	while(1)
	{
		//~ 延时一秒(1000000微秒), Windows下用Sleep()替代
		usleep(1000000); 
		//~ 获得当前时间
		time(&current_tm);
		//~ 按照自定义格式输出日期与时间到ftime[]中
		strftime(ftime, tm_len, " %Y-%B-%d, %A, %H:%M:%S", localtime(&current_tm)); 
		//~ 输出时间到终端
		cout<<ftime<<flush; 
		//~ 回车
		cout<<'\r'; 
	}
	return 0;
}
Tags: .
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Home

RFC: Request For Comments. Orz..

Name(required)
Mail (required),(will not be published)
Website(recommended)