这就是我想要的:
char *getHour(){
return ("%d:%d:%d",hour, min, sec);
}
返回这样的字符串 "hh:mm:ss" 我该怎么做?
一种可能的实现如下所示
编辑:结合戴夫对static
数组的建议,snprintf
并返回一个const char *
int hh = 5, mm = 45, ss = 20;
const char* getHour()
{
static char hourStr[32];
snprintf(hourStr,14, "%d:%d:%d\n", hh, mm, ss);
return hourStr;
}
如果您将此实现的输出打印为printf("GetHour: %s\n", getHour());
,您将得到GetHour: 5:45:20
我认为是您预期的输出。
我会假装你有充分的理由这样做。这是您要查找的代码:
char *getHourMinuteSecond( int hour, int minute, int second ) {
assert( hour >= 0 && hour < 24 );
assert( minute >= 0 && minute < 60 );
assert( second >= 0 && second <= 60 ); // leap seconds... maybe
char *output = (char *) malloc( 9 * sizeof( char ) );
if( output == NULL ) {
return NULL;
}
output[0] = (char) ((hour / 10) + '0');
output[1] = (char) ((hour % 10) + '0');
output[2] = ':';
output[3] = (char) ((minute / 10) + '0');
output[4] = (char) ((minute % 10) + '0');
output[5] = ':';
output[6] = (char) ((second / 10) + '0');
output[7] = (char) ((second % 10) + '0');
output[8] = '\0';
return output;
}
现在让我们将限制放宽到一些更理智的东西。我们可以使用 snprintf:
char *getHourMinuteSecond( int hour, int minute, int second ) {
assert( hour >= 0 && hour < 24 );
assert( minute >= 0 && minute < 60 );
assert( second >= 0 && second <= 60 ); // leap seconds... maybe
char *output = (char *) malloc( 9 * sizeof( char ) );
if( output == NULL ) {
return NULL;
}
snprintf( output, 9, "%02d:%02d:%02d", hour, minute, second );
return output;
}
让我们更加理智,并通过参数返回函数(这样我们就不需要玩了malloc
):
void getHourMinuteSecond( char target[9], int hour, int minute, int second ) {
assert( target != NULL );
assert( hour >= 0 && hour < 24 );
assert( minute >= 0 && minute < 60 );
assert( second >= 0 && second <= 60 ); // leap seconds... maybe
snprintf( target, 9, "%02d:%02d:%02d", hour, minute, second );
}
等等,最后一个功能主要是错误检查。我们可以再次变得愚蠢并使用#define
:
#define getHourMinuteSecond(tgt,h,m,s) snprintf(tgt,9,"%02d:%02d:%02d",h,m,s)
最后,在您的原始代码中,您不采用hour
,minute
或second
作为参数,所以也许您希望函数确定它们?
void getHourMinuteSecond( char target[9] ) {
assert( target != NULL );
const time_t now = time( 0 );
const tm *const tmnow = localtime( &now );
snprintf( target, 9, "%02d:%02d:%02d", tmnow->tm_hour, tmnow->tm_min, tmnow->tm_sec );
}
您可以只返回一个字符串,连接小时、分钟和秒,例如:
str = 小时 + 分钟 + 秒
要做到这一点,使用函数 strcat(destination, source) (#include) 会出现这样的情况:
char *getHour(....)
{
char str[20];
strcpy(str,hour);
strcat(str,":");
strcat(str,min);
strcat(str,":");
strcat(str,"sec);
return str;
}