时间:time

srand(time(NULL)); 随机数种子

    cout << rand()%100<< endl;

C++中获取本地时间是通过time(0)来获取的,但是time(0)获取到的是从1900年到现在的秒数,我们使用的时候需要把其转换成我们常见的格式 , 意味着我们需要现在时间的具体年,月,日,时,分,秒。在C++的库里有一个类#include<time.h>,其中给我们定义了转换方法;

首先认识一下:time(0),这句代码得意思是得到时间运行的秒数,可以直接cout<<time(0);看下效果;

我们获取本地时间的时候需要借助 struct tm 的格式:

 所以:time_t  ti=time(0);

tm *t=localtime(&ti); 这样我们就得到了本地的时间换算后的值,剩下的就简单了,需要什么调用什么:

比如:小时:t->tm_hour

struct tm

{
    int tm_sec;   // seconds after the minute - [0, 60] including leap second
    int tm_min;   // minutes after the hour - [0, 59]
    int tm_hour;  // hours since midnight - [0, 23]
    int tm_mday;  // day of the month - [1, 31]
    int tm_mon;   // months since January - [0, 11]
    int tm_year;  // years since 1900
    int tm_wday;  // days since Sunday - [0, 6]
    int tm_yday;  // days since January 1 - [0, 365]
    int tm_isdst; // daylight savings time flag
};

使用的时候代码报错:C4996   

把所报错误信息里的解决方案里的宏_CRT_SECURE_NO_WARNINGS添加到下图所指示的位置即可;

猜你喜欢

转载自blog.csdn.net/qq_41672557/article/details/80623244
今日推荐