문제

"hh : mm : ss"-문자 배열 (문자열)으로 현재 시간을 가져와야하므로 나중에 결과를 다음과 같이 출력 할 수 있습니다. printf("%s", timeString);

나는 꽤 혼란 스럽다 timeval 그리고 time_t 유형 BTW이므로 모든 설명은 굉장합니다 :)

편집 : 그래서 나는 Strftime 등을 시도했지만 약간 효과가있었습니다. 내 코드는 다음과 같습니다.

time_t current_time;
struct tm * time_info;
char timeString[8];

time(&current_time);
time_info = localtime(&current_time);

strftime(timeString, 8, "%H:%M:%S", time_info);
puts(timeString);

그러나 출력은 다음과 같습니다. "13 : 49 : 53a ?? j`A?"

"무슨 일이 일어나고 있는지"A ?? J`A?"결국?

도움이 되었습니까?

해결책

이 코드에서 쓰레기를 받고 있습니다.

time_t current_time;
struct tm * time_info;
char timeString[8];

time(&current_time);
time_info = localtime(&current_time);

strftime(timeString, 8, "%H:%M:%S", time_info);
puts(timeString);

문자열에서 널 터미네이터 ( 0)를위한 공간을 허용하지 않기 때문에 문자열이 인쇄 될 때 끝이 어디에 있는지 알지 못하고 문자열의 일부로 다음 메모리의 무작위 쓰레기를 inteprets합니다. .

이것으로 변경하십시오.

time_t current_time;
struct tm * time_info;
char timeString[9];  // space for "HH:MM:SS\0"

time(&current_time);
time_info = localtime(&current_time);

strftime(timeString, sizeof(timeString), "%H:%M:%S", time_info);
puts(timeString);

그리고 그것은 올바르게 작동합니다 strftime() A 0을 추가 할 공간이 충분합니다. 두 곳에서 숫자를 변경하는 것을 잊어 버리는 위험을 피하기 위해 Sizeof (Array)를 사용하고 있습니다.

다른 팁

살펴보십시오 스트프 프리 타임 기능을 통해 시간을 선택한 형식으로 숯 배열에 쓸 수 있습니다.

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

/* get seconds since the Epoch */
time_t secs = time(0);

/* convert to localtime */
struct tm *local = localtime(&secs);

/* and set the string */
sprintf(timeString, "%02d:%02d:%02d", local->tm_hour, local->tm_min, local->tm_sec);

시간을 다루기위한 중요한 유형 (프로세스/스레드 시간이 아닌 벽 클록 타임 유형)은 time_t 그리고 struct tm.
일부 작업을 사용하면 하나와 다른 한쪽으로 변환 할 수 있지만 현지 시간 대 UTC 시간에주의를 기울여야합니다.

살해 설명 <time.h>, 당신이 될 때까지 그 기능을 시도하십시오 그로크 C.의 시간

다시, UTC 시간과 현지 시간에주의를 기울이십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top