2016-05-31 36 views
1

我正在使用GetLocalTime(&time)函數來獲取時間visual C++。現在,我需要將輸入變高時的時間保存在另一個結構中,以便我可以對保存的時間進行進一步計算。如何在另一個結構中保存GetLocalTime時間

SYSTEMTIME time; 
if(input==high) 
{ 
    count++; //Incrementing a counter to count the number of times input is high 

    //Depending upon this count, I need to save value of time in a new variable 
    //using GetLocalTime to get current time 

    GetLocalTime(&time); 
} 

如何根據計數值存儲當前時間。就像計數爲1時一樣,這意味着首次輸入爲高,因此將其存儲在a1中。如果計數爲2,則存儲時間爲a2。如果計數爲5,則存儲時間爲a5。我不能使用開關,因爲案件不是固定的,可能有很多數量。我可以使用什麼其他邏輯來節省時間。

+0

使用容器?例如'array','vector'等 – Rotem

+0

@Rotem當count爲1時,我在數組中保存了時間,但當count爲2時它將覆蓋第一次的值。 ?或者可能是我沒有得到你想說的話。 –

+0

如果您使用'count'作爲數組的索引,或者改爲使用'vector :: push_back',則不適用。 – Rotem

回答

3

您應該使用容器,例如std::vector來存儲您的時間值。

std::vector<SYSTEMTIME> savedTimes; 

SYSTEMTIME time; 
if (input == high) 
{ 
    //count++; //count is redundant now, you can later just check savedTimes.size() 
    GetLocalTime(&time); 
    savedTimes.push_back(time); //will add another value to the end of the vector. 
} 

做一些與你的存儲時間:

for (auto it = savedTimes.begin(); it != savedTimes.end(); ++it) 
{ 
    SYSTEMTIME time = *it; 
    //whatever... 
} 

for (int i = 0; i < savedTimes.size(); i++) 
{ 
    SYSTEMTIME time = savedTimes[i]; 
    //whatever... 
} 
+0

這很棒。但是,我怎麼知道哪個savedTime是哪個計數值。此外,我還需要減去時間值,爲此我需要將它們轉換爲文件時間。是否有可能使用矢量? –

+0

@Andrew我加了一個例子,你也可以通過索引訪問矢量值,所以你知道哪個值是什麼索引。關於減法和文件時間,這與原始問題或向量無關。我建議你問一個討論這個問題的新問題,無論在容器中存儲多個值。 – Rotem

+0

我試過了我的自我,並添加了一個解決方案。請看看它。 –

-1

我以STRUC的陣列解決了這個問題功能。

struct foo 
{ 
    WORD Year; 
    WORD Month; 
    WORD DayOfWeek; 
    WORD Day; 
    WORD Hour; 
    WORD Minute; 
    WORD Second; 
    WORD Milliseconds; 
}; 

struct foo Foo[20] 

現在只要輸入高:

if(input==high) 
{ 
count++; 
GetLocalTime(&time); 


//This will copy complete time in Foo[0]. 
//So next time input is high, time will get copied in Foo[1] and this will keep on going.. 
memcpy(&Foo[count],&time,sizeof(Foo)); 

} 

現在我想知道如何清除結構Foo

+0

Downvoting是可以的,但請嘗試添加評論,以便我能理解我在邏輯中做了什麼錯誤。 –

相關問題