我这里有一个问题,我一直在尝试比较来自 SYSTEMTIME
的日期格式和来自文本文件(string
)的日期。但它不起作用。我尝试将两者都更改为字符串(使用 osstringstream
)、char*
和 int(使用 sscanf
)来进行比较,但没有成功。它非常简单,我想做的就是获取当前系统日期并将其与文本文件中的日期进行比较。下面是我的代码:
char szcurrentDate[MAX_PATH] = "";
char szdate_time[MAX_PATH];
SYSTEMTIME st;
GetLocalTime(&st);
GetDateFormat(LOCALE_USER_DEFAULT, NULL, &st, "yyyy-M-d ", szcurrentDate,
MAX_PATH); // current system date
// std::ostringstream mm;
// stringstream mm;
// mm << szcurrentDate;
MessageBoxA(NULL, szcurrentDate, "Attention", IDOK == IDCANCEL);
ifstream ifs(szFile);
string line;
while (!ifs.eof())
{
getline(ifs, line);
if ((line.find("TESTING_GET_DATE:") != string::npos))
{
std::string str = line.substr(
17, 9); // substract TESTING_GET_DATE: 2014-3-16 to 2014-3-16
strcpy(szdate_time, str.c_str());
if (szcurrentDate == szdate_time)
{
MessageBoxA(NULL, "Same", "Attention", MB_OK);
}
else
{
MessageBoxA(NULL, "blablabla", "Attention", MB_OK);
}
注意:我尝试只显示 szcurrentDate
和 szdate_time
它们显示的日期完全相同。 string
,char*
或 int
格式。
最佳答案
这个:
strcpy(szdate_time, str.c_str());
if (szcurrentDate == szdate_time)
没有意义。您正在(不必要地)将 C++ 字符串复制到 C 字符串,然后比较指向两个 char 数组的指针(它们永远不会相等,因为不比较内容,只比较地址)。
你可以这样修复它:
if (szcurrentDate == str)
这将为 std::string 调用 operator==
,它比较字符串内容。而且代码更少。
关于c++ - 比较来自字符串、char* 或 int 的 2 个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22433578/