开发者

I want to use sprintf to pull out a string from NSString instead of using UTF8String?

I want to use sprintf to pull out a string from NSString instead of using UTF8String? I know this works:

NSString *nsSDummy = [[NSString alloc] initWithObjects: @"red"];
char *strDummy;

strDummy = [nsSDummy UTF8String];
开发者_开发百科

But want to do the following:

NSString *nsSDummy = [[NSString alloc] initWithObjects: @"red"];
char *strDummy;

sprintf(strDummy, "%@", nsSDummy); <<--Unknown conversion type character "@" in format

thanks


can't be done that way, as sprintf dosn't know anything about Cocoa data types.

you can use NSString's stringWithFormat, or NSMutableString's appendFormat: method then use that constructed string to create the cString, i.e.

NSString *nsSDummy = @"red";
NSString *derivedString = [NSString stringWithFormat: "%@",nsSDummy];
char *strDummy = [derivedString UTF8String];


You can't.

In the case you posted, there is no reason to use sprintf. Just use UTF8String and be done with it. In a more complicated case, use NSString's stringWithFormat: method and then use UTF8String on the resulting NSString.

I hope it's just a result of trimming for the post, but you're using sprintf completely incorrectly (you're passing it an uninitialized pointer) and will wind up with a crash or worse. And you really should use snprintf or asprintf instead anyway.


You must alloc strDummy or do this way

int len = 10;
char[len] _strDummy;
char *strDummy = &_strDummy;
//...and continue your code

Good look!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜