I want to code vsnprintf function, using NSString.
This is my implementation of vsnprintf :
int my_vsnprintf(char *buffer, size_t count, const char *format, ...)
{
int iRet;
va_list ap;
NSString *pnssBuffer=NULL;
NSString *pnssFormat;
const char *pcszBuffer;
/* Format with NSString */
pnssFormat=[NSString stringWithCString:format
encoding:NSUTF8StringEncoding];
va_start(ap, format);
pnssBuffer=[[NSString alloc] initWithFormat:pnssFormat arguments:ap];
/* Copy to char * */
pcszBuffer=[pnssBuffer cStringUsingEncoding:NSUTF8StringEncoding];
memcpy(buffer, pcszBuffer, count);
iRet=strlen(buffer);
/* Free */
[pnssBuffer release];
va_end(ap);
return iRet;
}
When I call it with char * param, it works :
my_vsnprintf(buffer, 256, "hello %s", "world");
NSLog(@"buffer = %s", buffer);
print correctly this : buffer = hello world
But when I call it with wchar_t * param, I only get fist character of world
my_vsnprintf(buffer, 256, "hello %ls", L"world");
NSLog(@"buffer = %s", buffer);
print this : buffer = hello w
I don’t understand why, any help for my function ?
According to String Format Specifiers in the “String Programming Guide”,
initWithFormat:arguments:and friends do not support the “%ls” format. In fact, the “l” modifier is ignored here.There is a “%S” format, but that is for a sequence of 16-bit Unicode characters, so you cannot use it for
wchar_teither.ADDED
wchar_tis 4-byte Unicode (little endian) on the iPhone and the Simulator, therefore you can convert it toNSStringas follows: