2013-03-12 3 views
0

다음의 방법으로 현재의 특정 시간까지 남은 시간 (초)을 반환 할 것으로 기대합니다. 예를 들어, 현재 시간이 "19:00"이면, GetRemainedSeconds("19:01")은 60을 반환해야 60 초가 주어진 시간까지 남았음을 나타냅니다. GetRemainedSeconds("18:59")을 호출하면 -60이 반환됩니다. 문제는 다음 함수가 임의의 동작을 보이고 있다는 것입니다. 때로는 올바른 값을 반환하지만 때로는 동일하지 않습니다 (동일한 컴퓨터에서 실행되는 경우에도 마찬가지 임). 이 코드의 문제점은 무엇입니까? 당신은 그냥 초기화되지 않은 쓰레기 인 자체에 when.tm_isdst을 설정하는지정된 시간까지 남아있는 초를 얻는 방법

when.tm_isdst = when.tm_isdst; 

:

int GetRemainedSeconds (const std::string &timeString, bool &isValid) 
{ 
    struct tm when; 
    char* p; 

    p = strptime (timeString.c_str(), "%H:%M", &when); 

    if (p == NULL || *p != '\0') 
    { 
     std::cout << "Invalid 24h time format" << std::endl; 
     isValid = false; 
     return 0; 
    } 

    struct tm now; 

    isValid = true; 
    time_t nowEpoch = time (0); // current epoch time 

    struct tm tmpTime; 
    now = *localtime_r (&nowEpoch, &tmpTime); 

    when.tm_year = now.tm_year; 
    when.tm_mon = now.tm_mon; 
    when.tm_mday = now.tm_mday; 
    when.tm_zone = now.tm_zone; 
    when.tm_isdst = now.tm_isdst; 
    time_t whenEpoch = mktime (&when); 

    return (whenEpoch - nowEpoch); 
} 

답변

2

당신은 뭔가 (아마도 제로)으로 when.tm_sec를 설정해야합니다. 그것은 당신이 원하는 것이 아닌 이전 전화에서 스택에있는 모든 쓰레기를 포함합니다.

네, 또한 when.tm_isdst을 의미있는 것으로 설정해야합니다.

0

여기에 하나의 문제입니다.

나는 당신이 말하는 의미 생각 :

when.tm_isdst = now.tm_isdst; 
+0

당신이 맞습니다. 오타였습니다. – Meysam

관련 문제