2011-09-19 34 views
0

我想將本地時間保存爲char變量。這裏是我使用的代碼。但跟它將系統時間存儲到cpp中的變量中

「不能轉換的char *爲char」

這裏是我的代碼:

#include <stdio.h> 
#include <time.h> 

struct tme 
{ 
    char intime; 
}e; 
void main() 
{ 

    char timeStr [9]; 
_strtime(timeStr); 
    e.intime=timeStr; 
    printf("The current time is %s \n", timeStr); 
} 

Thanx提前。

+0

請注意'_strtime'是一個Windows函數,它使您的代碼片段不符合標準。請考慮使用'const time_t current = time(NULL); strftime(timeStr,9,「%H:%M:%S」,localtime(&current));',即使它看起來像一小撮,因爲它不會不必要地依賴於(不推薦使用的)僅限Windows的函數。 – DevSolar

回答

0

這很簡單,你有一個長度爲9的char數組timeStr並試圖將它分配給char intime。有類型不兼容。把它想象爲char[]永遠不會等於char

你可以解決這個問題如下(但我不知道你想達到的目標):

struct tme 
{ 
    char* intime; 
}e; 

PS:MSDN指出(_strtime):

//注意:_strtime已棄用;考慮使用_strtime_s代替

0
e.intime=timeStr; 

timeStrchar [9]類型。它在指定期間或在用作參數的函數調用期間衰減爲指向第一個元素的指針。

e.intimechar的類型。 charchar*不是類型兼容的,編譯器在抱怨你。相反,你可以做 -

struct tme 
{ 
    char intime[10]; // +1 for the termination character to play safe 
}e; 

現在,strcpy可以用來將時間複製到成員變量。

strcpy(e.intime, timeStr); 

如果是C++,使用的std :: string而不是原始陣列。

+0

緩衝區大小爲9就足夠了:六位數字,兩個冒號和一個空字符。 –

+0

如果需要額外的終止字符,那麼它是不安全的(因爲timeStr不會有終止空,所以strcpy可能會覆蓋超過10個字符)。但實際上,strTime保證以null結尾,所以9個字符就足夠了。 – TonyK

+0

@TonyK - strcpy從不會被覆蓋,因爲它在目標空間還剩下一些。它只是將源複製到目的地,直到源被'\ 0'命中。 – Mahesh

0

細化的某些階段:

第1階段:修復您的代碼。

struct tme { 
    char * intime; // You had a type mismatch 
} e; 

int main() { // Don't use void main() 
    char timeStr [9]; 
_strtime(timeStr); 
    e.intime=timeStr; 
    printf("The current time is %s \n", timeStr); 
} 

這裏有一個問題:你的struct tme是依靠外部世界爲它做的一切,並因此正確地做。如果我們想重用主要的timeStr會怎麼樣?如果在除main之外的其他功能中使用此結構,並將e.intime設置爲超出範圍的變量,該怎麼辦?

細化:struct tme應該擁有時間緩衝區。

struct tme { 
    char intime[9]; // Put the buffer here, not in main. 
} e; 

int main() { 
    _strtime(e.intime); 
    printf("The current time is %s \n", e.intime); 
} 

這裏我們還是有問題。任何人都可以修改該緩衝區,而且該結構只是一個無源插座。

細化:隱藏數據並使對象處於活動狀態。

struct tme { 
    const char * set_time() { _strtime (intime); return intime; } 
    const char * get_time() const { return intime; } 
private: 
    char intime[9]; 
}; 

int main() { 
    printf("The current time is %s \n", e.set_time()); 
} 
相關問題