정련의 단계 :
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());
}
'_strtime'은 Windows 기능이며, 코드 스 니펫을 비표준으로 렌더링합니다. 친절하게'const time_t current = time (NULL); (비추천) Windows 전용 함수에 따라 불필요하게 코드가 작성되지 않기 때문에 strftime (timeStr, 9, "% H : % M : % S", localtime (& current)); . – DevSolar