C++ time()

C++ 中的 time() 函数以 time_t 类型对象的形式返回当前日历时间。它定义在 ctime 头文件中。

示例

#include <iostream>
#include <ctime>
using namespace std;

int main() {

  // use time() with NULL argument
  cout << time(NULL);

  return 0;
}

// Output: 1629799688

time() 语法

time() 函数的语法是

time(time_t* arg);

time() 参数

time() 函数接受以下参数

  • arg:一个指向 time_t 对象的 指针,该对象(如果不是 NULL)存储时间。

time() 返回值

time() 函数返回

  • 成功时 - 当前日历时间,作为 time_t 类型的值。
  • 失败时 - -1,该值被强制转换为 time_t 类型。

time() 原型

time() 在 ctime 头文件中定义的原型是

time_t time(time_t* arg);

示例 1:C++ time()

#include <iostream>
#include <ctime>
using namespace std;

int main() {
  time_t current_time;

current_time = time(NULL);
cout << current_time; cout << " seconds has passed since 00:00:00 GMT, Jan 1, 1970"; return 0; }

输出

1629810340 seconds has passed since 00:00:00 GMT, Jan 1, 1970

示例 2:C++ time() 带引用指针

#include <iostream>
#include <ctime>
using namespace std;

int main() {
  time_t current_time;

// stores time in current_time time(&current_time);
cout << current_time; cout << " seconds has passed since 00:00:00 GMT, Jan 1, 1970"; return 0; }

输出

1629810340 seconds has passed since 00:00:00 GMT, Jan 1, 1970

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战