【发布时间】:2017-12-07 20:35:54
【问题描述】:
我有 myPrint 的功能,我正在尝试使用,但我认为我使用 strtok 功能错误
int myPrint( const char* format , ...)
{
char str[BUFFER];
char cpy[BUFFER] = {0};
char convert[BUFFER];
char *check;
char tempFormat[BUFFER];
int len = 0;
char *tempCheck;
va_list args;
va_start( args , format);
strcpy(tempFormat , format );
check = strtok ( tempFormat , "%");
int flag = 0;
while( check != NULL)
{
strcat( cpy , check );
len = strlen( cpy );
switch( tempFormat[len + 1] )
{
case 'd':
sprintf( convert , "%d" , va_arg( args , int) );
strcat( cpy , convert);
break;
case 'f':
sprintf( convert , "%f" , va_arg( args, double ));
strcat( cpy , convert);
break;
case '%':
strcat( cpy ,"%" );
break;
case 's':
strcat( cpy ,va_arg( args , char* ) );
break;
default:
break;
}
check = strtok ( NULL , "%");
}
printf("%s" , cpy);
va_end( args);
}
void main()
{
int x = 7;
float y = 11;
char str[] ="HELLo";
char str2[]="MY NAME";
myPrint ( "ss %d is %d %s " , 7 , 6 , str);
}
问题是如果我发送到函数来打印我想要的东西,我会在每个% 之后得到d
有没有办法将strtok调用的结果向前移动一个位置?
【问题讨论】:
-
(check + 1)?? -
如果我这样做,我会得到分段错误(核心转储)
-
你需要检查你不是在最后,并且实际上有一个角色可以移动,例如
if (*check && *(check + 1)) { /* then use check + 1 (or just check++) */ } -
做到了。没有帮助
-
我们必须猜测
BUFFER足以容纳strcpy(tempFormat , format );然后check = strtok ( tempFormat , "%");将指向组成字符串的字符直到第一个@987654332 @字符。 (strtok将在解析期间将'%'替换为'\0')。If (check && *check && *(check + 1)) { /* then it is fine to use *(check + 1) -- which is the 2nd char in the string pointed to by check */ }