我一直在尝试使用C++获取当前日期,但我无法弄清楚自己在做什么错。我已经查看了几个站点,并且实现了所有解决方案,但出现错误消息:“此函数或变量可能不安全。考虑改用localtime_s。”我尝试了找到here的几种解决方案(包括以下解决方案),但是我无法使它们起作用。我究竟做错了什么?
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
using namespace std;
int main()
{
const int SALARY = 18;
const int COMMISSION = .08;
const int BONUS = .03;
int monthlySales;
int appointmentNumber;
time_t t = time(0); // get time now
struct tm * now = localtime(&t);
string name;
//this is where the user adds their name and date
cout << "Please enter the sales representative's name: ";
cin >> name;
cout << "Please enter the number of appointments: ";
cin >> appointmentNumber;
cout << "Please enter the amount of sales for the month: $";
cin >> monthlySales;
//clear screen and execute code
system("cls");
cout << setfill(' ');
cout << "Sales Representative:" << name << endl;
cout << "Pay Date:" << (now->tm_mon + 1) << " " << now->tm_mday << " " << (now->tm_year + 1900) << endl;
cout << "Work Count:" << appointmentNumber << "Sale Amount"
<< monthlySales << endl;
system("pause");
return 0;
}
最佳答案
您可以尝试下面的代码和说明。
#include <iostream>
#include <ctime>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,80,"%d-%m-%Y %I:%M:%S",timeinfo);
std::string str(buffer);
std::cout << str;
return 0;
}
函数
time_t时间(time_t *计时器);
函数将返回此值,并且如果参数不是空指针,则还将此值设置为timer指向的对象。
参数
指向时间类型为time_t的对象的指针,该对象存储了时间值。如果不需要
返回值
当前日历时间作为time_t对象。如果该函数无法检索日历时间,则返回值-1。