与时间一起工作

Working with time

本文关键字:工作 一起 时间      更新时间:2023-10-16

我开发了一个c++应用程序在23:01:50打印Hello

我的代码

#include<iostream>
#include<string>
#include <time.h>
#include <windows.h>
using namespace std;
int main ()
{
    time_t start = time (&start);
    cout<<ctime(&start);
    while(1)
    {
        time (&start);
        if( ctime(&start) == "Fri Jan 18 23:01:50 2013n" )
            cout << "Hello";
        Sleep(500);
        cout << ctime(&start);
    }
}

但是输出是:

Fri Jan 18 23:01:49 2013
Fri Jan 18 23:01:49 2013
Fri Jan 18 23:01:50 2013
Fri Jan 18 23:01:50 2013
Fri Jan 18 23:01:51 2013
Fri Jan 18 23:01:51 2013

为什么不打印Hello ?

谢谢

在c++中,相等操作符"=="不能像您期望的那样用于char指针(这是您正在使用的)。它比较的是指针,这些指针实际上指向内存中的不同位置。要比较字符串(顺便说一句,这不是执行此检查的最佳方法),您需要使用字符串比较函数。

例如:

if (strcmp(ctime(&start), "Fri Jan 18 23:01:50 2013n") == 0)
{
}

更多信息请参见:http://www.cplusplus.com/reference/cstring/strcmp/

==改为strcmp(ctime(...), "Fri Jan 18...") == 0。你不能比较c-string和==,因为它比较的是地址而不是值。

if( strcmp(ctime(&start), "Fri Jan 18 23:01:50 2013n") == 0 )